package org.bigdata.framework.core.protocol;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.request.AbstractUpdateRequest;
import org.apache.solr.client.solrj.request.ContentStreamUpdateRequest;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.bigdata.framework.core.elasticsearch.ESQueryBuilderConstructor;
import org.bigdata.framework.core.elasticsearch.ESQueryBuilders;
import org.bigdata.framework.core.elasticsearch.ElasticSearchService;
import org.bigdata.framework.core.mapper.custom.DynamicMapper;
import org.bigdata.framework.core.model.BaikeEntry;
import org.bigdata.framework.core.model.Classes;
import org.bigdata.framework.core.model.CommonDataProperty;
import org.bigdata.framework.core.model.CommonObjectProperty;
import org.bigdata.framework.core.model.DataHandling;
import org.bigdata.framework.core.model.DataProperty;
import org.bigdata.framework.core.model.DataSubmit;
import org.bigdata.framework.core.model.DataType;
import org.bigdata.framework.core.model.Dict;
import org.bigdata.framework.core.model.DictItem;
import org.bigdata.framework.core.model.GeneralWord;
import org.bigdata.framework.core.model.GeneralWordCategory;
import org.bigdata.framework.core.model.ObjectProperty;
import org.bigdata.framework.core.model.ShardingDataSource;
import org.bigdata.framework.core.model.ShardingRepositoryCount;
import org.bigdata.framework.core.model.ShardingRepositoryDataSource;
import org.bigdata.framework.core.model.ThesauriWord;
import org.bigdata.framework.core.model.ThesauriWordCategory;
import org.bigdata.framework.core.model.ThesauriWordReference;
import org.bigdata.framework.core.model.User;
import org.bigdata.framework.core.service.IDataHandlingService;
import org.bigdata.framework.core.utils.CodeUtils;
import org.bigdata.framework.core.utils.DBUtils;
import org.bigdata.framework.core.utils.DateUtils;
import org.bigdata.framework.core.utils.DbConnection;
import org.bigdata.framework.core.utils.FieldPrefixUtils;
import org.bigdata.framework.core.utils.IdWorker;
import org.bigdata.framework.core.utils.JdbcUtils;
import org.bigdata.framework.core.utils.LangDetectUtils;
import org.bigdata.framework.core.utils.MongoClientUtils;
import org.bigdata.framework.core.utils.MongoVersionClientUtils;
import org.bigdata.framework.core.utils.SQLAdapter;
import org.bigdata.framework.core.utils.UnicodeConverter;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;

import com.baomidou.mybatisplus.mapper.SqlRunner;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.xxl.conf.core.XxlConfClient;

public class DynamicService extends SqlRunner implements IDynamicService {

	private static final Logger LOG = Logger.getLogger(DynamicService.class);

	/**
	 * 存储类、数据属性、对象属性、字典项和solr对应关系
	 */
	private HashMap<String, Object> dataSchema = new HashMap<String, Object>();

	@Autowired
	private com.alibaba.druid.pool.DruidDataSource dds;
	@Autowired
	private PublicService publicService;
	@Autowired
	private BaseService baseService;
	@Autowired
	private DynamicMapper dynamicMapper;
	@Autowired
	private IDataHandlingService dataHandlingService;
	@Autowired
	private IBaikeService baikeService;
	@Autowired
	private IWordService wordService;
	// solr初始化
	private static HttpSolrClient server = new HttpSolrClient.Builder(
			XxlConfClient.get("dal.solr.storage.properties",
					"http://127.0.0.1:8983/solr/hymax")).build();
	// private static SolrClient server = new
	// HttpSolrClient(XxlConfClient.get("dal.solr.storage.properties",
	// "http://127.0.0.1:8983/solr/hymax"));
	// 关键词solr核
	private static HttpSolrClient kwServer = new HttpSolrClient.Builder(
			XxlConfClient.get("dal.solr.keywords.properties",
					"http://127.0.0.1:8983/solr/keywords")).build();
	// 词表solr核
	private static HttpSolrClient wordServer = new HttpSolrClient.Builder(
			XxlConfClient.get("dal.solr.word.properties",
					"http://127.0.0.1:8983/solr/word")).build();
	// 百科solr核心
	private static HttpSolrClient baikeServer = new HttpSolrClient.Builder(
			XxlConfClient.get("dal.solr.baike.properties",
					"http://127.0.0.1:8983/solr/baike")).build();
	// 自动标引api
	private static HttpSolrClient indexingServer = new HttpSolrClient.Builder(
			"http://127.0.0.1:8983/solr/indexWeight").build();

	// 数据库类型
	private static String dbStyle = XxlConfClient.get("dal.db.style", "mysql");
	// 数据库类型
	private static String jdbcUrl = XxlConfClient.get("dal.jdbc.url", "");
	// 数据库类型
	private static String jdbcUserName = XxlConfClient.get("dal.jdbc.username", "");
	// 数据库类型
	private static String jdbcPassWord = XxlConfClient.get("dal.jdbc.password", "");

	
	// 知识库数据是否启用mongodb存储（百万以上数据采用这种方式）
	private static boolean isMongodbstorage = Boolean
			.parseBoolean(XxlConfClient.get("dal.is.mongodb.storage", "false"));
	// 知识库前缀
	private static String repositoryPrefix = XxlConfClient.get(
			"dal.repository.prefix", "hymax");
	// mongo库名称
	private static String mongoDbName = XxlConfClient.get("dal.mongo.dbname",
			"dal_hymax");
	// mongo库名称-version
	private static String mongoDbNameVersion = XxlConfClient.get(
			"dal.mongo.dbname" + "_version", "dal_hymax_version");
	// mongo数据库连接URL
	private static String mongoHostPort = XxlConfClient.get(
			"dal.mongo.hostport", "127.0.0.1:27017");

	// es集群名称
	private static String elasticsearchClusterName = XxlConfClient.get(
			"dal.elasticsearch.cluster.name", "elasticsearch");
	// es服务器ip
	private static String elasticsearchHostIp = XxlConfClient.get(
			"dal.elasticsearch.host.ip", "127.0.0.1");
	// es服务器端口
	private static String elasticsearchHostPort = XxlConfClient.get(
			"dal.elasticsearch.host.port", "9300");

	// mongo连接
	MongoDatabase aMongoDatabase = MongoClientUtils.getMongoDatabaseConnection(
			mongoHostPort.split(":")[0],
			Integer.parseInt(mongoHostPort.split(":")[1]), mongoDbName);
	// mongo连接-version
	MongoDatabase aMongoDatabaseVersion = MongoVersionClientUtils
			.getMongoDatabaseConnection(mongoHostPort.split(":")[0],
					Integer.parseInt(mongoHostPort.split(":")[1]),
					mongoDbNameVersion);
	// es连接
	ElasticSearchService aElasticSearchService = new ElasticSearchService(
			elasticsearchClusterName, elasticsearchHostIp,
			Integer.parseInt(elasticsearchHostPort));

	SQLAdapter aSQLAdapter = null;
	IdWorker aIdWorker = new IdWorker(2);

	@Override
	public List<SolrInputDocument> getIndexData(String classesEn,
			List<Map<String, Object>> list) {
		return getIndexData(classesEn, list, null, null);
	}

	@Override
	public void commitIndex() {
		try {
			server.commit(false, false);
		} catch (Exception e) {
			LOG.error("发布索引失败.", e);
			e.printStackTrace();
		}
	}

	@Override
	public void commitWordIndex() {
		try {
			wordServer.commit(false, false);
		} catch (Exception e) {
			LOG.error("发布索引失败.", e);
			e.printStackTrace();
		}
	}

	@Override
	public void commitBaikeIndex() {
		try {
			baikeServer.commit(false, false);
		} catch (Exception e) {
			LOG.error("发布索引失败.", e);
			e.printStackTrace();
		}
	}

	@Override
	public void commitKwIndex() {
		try {
			kwServer.commit(false, false);
		} catch (Exception e) {
			LOG.error("发布索引失败.", e);
			e.printStackTrace();
		}
	}

	@Override
	public void submitIndex(List<SolrInputDocument> list) {
		try {
			server.add(list);
			// server.commit(false, false);
		} catch (Exception e) {
			LOG.error("批量创建索引失败.", e);
			e.printStackTrace();
		}
	}

	@Override
	public void submitCommitIndex(String classesEn,
			List<Map<String, Object>> list) {
		List<SolrInputDocument> indexData = getIndexData(classesEn, list);
		try {
			server.add(indexData);
			// server.commit(false, false);
			// commitIndex();
		} catch (Exception e) {
			LOG.error("批量创建索引失败.", e);
			e.printStackTrace();
		}
	}

	public void submitKwIndex(List<SolrInputDocument> list) {
		try {
			kwServer.add(list);
			// server.commit(false, false);
		} catch (Exception e) {
			LOG.error("批量创建索引失败.", e);
			e.printStackTrace();
		}
	}

	private List<SolrInputDocument> buildGeneralWord(List<GeneralWord> list) {
		List<SolrInputDocument> gwIndexList = new ArrayList<SolrInputDocument>();
		SolrInputDocument aSolrInputDocument = null;

		for (int j = 0; j < list.size(); j++) {
			aSolrInputDocument = new SolrInputDocument();
			GeneralWord aGeneralWord = list.get(j);
			aSolrInputDocument.addField("id", "gw_" + aGeneralWord.getId());
			aSolrInputDocument.addField("stringIS_word_name", aGeneralWord
					.getWordName().toLowerCase());
			aSolrInputDocument.addField("stringIS_word_pinyin",
					aGeneralWord.getWordPinyin());
			if (aGeneralWord.getWordEnglish() != null) {
				aSolrInputDocument.addField("stringIS_word_english",
						aGeneralWord.getWordEnglish().toLowerCase());
			} else {
				aSolrInputDocument.addField("stringIS_word_english",
						aGeneralWord.getWordEnglish());
			}

			aSolrInputDocument.addField("stringIS_word_initial",
					aGeneralWord.getWordInitial());
			aSolrInputDocument.addField("stringITS_word_scope_note",
					aGeneralWord.getWordScopeNote());
			// 分类信息
			GeneralWordCategory aGeneralWordCategory = wordService
					.findGeneralWordCategory(aGeneralWord
							.getGeneralWordCategoryId());
			if (aGeneralWordCategory != null) {
				aSolrInputDocument.addField("stringIS_category_name",
						aGeneralWordCategory.getCategoryName());
				aSolrInputDocument.addField("stringIS_category_sid",
						aGeneralWordCategory.getCategorySid());
			}
			// 类型
			aSolrInputDocument.addField("type", "generalWord");
			gwIndexList.add(aSolrInputDocument);
		}

		return gwIndexList;
	}

	private List<SolrInputDocument> buildThesauriWord(List<ThesauriWord> list) {
		List<SolrInputDocument> twIndexList = new ArrayList<SolrInputDocument>();
		SolrInputDocument aSolrInputDocument = null;
		for (int j = 0; j < list.size(); j++) {
			aSolrInputDocument = new SolrInputDocument();
			ThesauriWord aThesauriWord = list.get(j);

			aSolrInputDocument.addField("id", "tw_" + aThesauriWord.getId());
			aSolrInputDocument.addField("stringIS_word_name", aThesauriWord
					.getWordName().toLowerCase());
			aSolrInputDocument.addField("stringIS_is_top_term",
					aThesauriWord.getIsTopTerm());
			aSolrInputDocument.addField("stringIS_word_pinyin",
					aThesauriWord.getWordPinyin());
			if (aThesauriWord.getWordEnglish() != null) {
				aSolrInputDocument.addField("stringIS_word_english",
						aThesauriWord.getWordEnglish().toLowerCase());
			} else {
				aSolrInputDocument.addField("stringIS_word_english",
						aThesauriWord.getWordEnglish());
			}

			aSolrInputDocument.addField("stringITS_usage_note",
					aThesauriWord.getUsageNote());
			aSolrInputDocument.addField("stringITS_scope_note",
					aThesauriWord.getScopeNote());
			aSolrInputDocument.addField("stringITS_historical_note",
					aThesauriWord.getHistoricalNote());
			if (null != aThesauriWord.getWordPid()
					&& !"".equals(aThesauriWord.getWordPid())) {
				aSolrInputDocument.addField("stringIS_word_pid", "tw_"
						+ aThesauriWord.getWordPid());
			}

			// 是否正式主题词
			aSolrInputDocument.addField("stringITS_word_formal",
					aThesauriWord.getWordFormal());
			// 范畴
			String[] thesauriWordCategoryArray = null;
			String[] wordCategorySid = null;
			String[] wordCategoryName = null;
			String wordCategoryInfo = "";
			if (null != aThesauriWord.getThesauriWordCategoryIds()
					&& !"".equals(aThesauriWord.getThesauriWordCategoryIds())
					&& aThesauriWord.getThesauriWordCategoryIds().contains(";")) {
				thesauriWordCategoryArray = aThesauriWord
						.getThesauriWordCategoryIds().split(";");
				wordCategorySid = new String[thesauriWordCategoryArray.length];
				wordCategoryName = new String[thesauriWordCategoryArray.length];

				for (int k = 0; k < thesauriWordCategoryArray.length; k++) {
					if (thesauriWordCategoryArray[k] != null
							&& !"".equals(thesauriWordCategoryArray[k])) {
						HashMap<String, Object> queryParams = new HashMap<String, Object>();
						queryParams.put("=,categorySid",
								thesauriWordCategoryArray[k]);
						List<ThesauriWordCategory> thesauriWordCategoryList = wordService
								.getThesauriWordCategory(queryParams, 1, 1);
						if (thesauriWordCategoryList.size() > 0) {
							wordCategorySid[k] = thesauriWordCategoryList
									.get(0).getCategorySid();
							wordCategoryName[k] = thesauriWordCategoryList.get(
									0).getCategoryName();
							wordCategoryInfo += thesauriWordCategoryList.get(0)
									.getCategorySid()
									+ "∷"
									+ thesauriWordCategoryList.get(0)
											.getCategoryName() + "≡";
						}

					}
				}
			}

			// 多值
			aSolrInputDocument.addField("stringIMS_category_sid",
					wordCategorySid);
			aSolrInputDocument.addField("stringIMS_category_name",
					wordCategoryName);
			aSolrInputDocument.addField("stringIS_category_info",
					wordCategoryInfo);

			// 叙词表关系
			HashMap<String, Object> yQueryParams = new HashMap<String, Object>();
			yQueryParams.put("=,thesauriWordId", aThesauriWord.getId());
			yQueryParams.put("=,referenceRelationLabel", "Y");
			List<ThesauriWordReference> yList = wordService
					.getThesauriWordReference(yQueryParams, 1,
							Integer.MAX_VALUE);
			String[] yWordNameStr = new String[yList.size()];
			for (int k = 0; k < yList.size(); k++) {
				ThesauriWordReference aThesauriWordReference = yList.get(k);
				ThesauriWord tThesauriWord = wordService
						.findThesauriWord(Integer
								.parseInt(aThesauriWordReference
										.getReferenceWordId()));
				yWordNameStr[k] = tThesauriWord.getWordName();
			}
			aSolrInputDocument.addField("stringIMS_reference_y", yWordNameStr);

			HashMap<String, Object> dQueryParams = new HashMap<String, Object>();
			dQueryParams.put("=,thesauriWordId", aThesauriWord.getId());
			dQueryParams.put("=,referenceRelationLabel", "D");
			List<ThesauriWordReference> dList = wordService
					.getThesauriWordReference(dQueryParams, 1,
							Integer.MAX_VALUE);
			String[] dWordNameStr = new String[dList.size()];
			for (int k = 0; k < dList.size(); k++) {
				ThesauriWordReference aThesauriWordReference = dList.get(k);
				ThesauriWord tThesauriWord = wordService
						.findThesauriWord(Integer
								.parseInt(aThesauriWordReference
										.getReferenceWordId()));
				dWordNameStr[k] = tThesauriWord.getWordName();
			}
			aSolrInputDocument.addField("stringIMS_reference_d", dWordNameStr);

			HashMap<String, Object> sQueryParams = new HashMap<String, Object>();
			sQueryParams.put("=,thesauriWordId", aThesauriWord.getId());
			sQueryParams.put("=,referenceRelationLabel", "S");
			List<ThesauriWordReference> sList = wordService
					.getThesauriWordReference(sQueryParams, 1,
							Integer.MAX_VALUE);
			String[] sWordNameStr = new String[sList.size()];
			for (int k = 0; k < sList.size(); k++) {
				ThesauriWordReference aThesauriWordReference = sList.get(k);
				ThesauriWord tThesauriWord = wordService
						.findThesauriWord(Integer
								.parseInt(aThesauriWordReference
										.getReferenceWordId()));
				sWordNameStr[k] = tThesauriWord.getWordName();
			}
			aSolrInputDocument.addField("stringIMS_reference_s", sWordNameStr);

			HashMap<String, Object> fQueryParams = new HashMap<String, Object>();
			fQueryParams.put("=,thesauriWordId", aThesauriWord.getId());
			fQueryParams.put("=,referenceRelationLabel", "F");
			List<ThesauriWordReference> fList = wordService
					.getThesauriWordReference(fQueryParams, 1,
							Integer.MAX_VALUE);
			String[] fWordNameStr = new String[fList.size()];
			for (int k = 0; k < fList.size(); k++) {
				ThesauriWordReference aThesauriWordReference = fList.get(k);
				ThesauriWord tThesauriWord = wordService
						.findThesauriWord(Integer
								.parseInt(aThesauriWordReference
										.getReferenceWordId()));
				fWordNameStr[k] = tThesauriWord.getWordName();
			}
			aSolrInputDocument.addField("stringIMS_reference_f", fWordNameStr);

			HashMap<String, Object> cQueryParams = new HashMap<String, Object>();
			cQueryParams.put("=,thesauriWordId", aThesauriWord.getId());
			cQueryParams.put("=,referenceRelationLabel", "C");
			List<ThesauriWordReference> cList = wordService
					.getThesauriWordReference(cQueryParams, 1,
							Integer.MAX_VALUE);
			String[] cWordNameStr = new String[cList.size()];
			for (int k = 0; k < cList.size(); k++) {
				ThesauriWordReference aThesauriWordReference = cList.get(k);
				ThesauriWord tThesauriWord = wordService
						.findThesauriWord(Integer
								.parseInt(aThesauriWordReference
										.getReferenceWordId()));
				cWordNameStr[k] = tThesauriWord.getWordName();
			}
			aSolrInputDocument.addField("stringIMS_reference_c", cWordNameStr);

			HashMap<String, Object> zQueryParams = new HashMap<String, Object>();
			zQueryParams.put("=,thesauriWordId", aThesauriWord.getId());
			zQueryParams.put("=,referenceRelationLabel", "Z");
			List<ThesauriWordReference> zList = wordService
					.getThesauriWordReference(zQueryParams, 1,
							Integer.MAX_VALUE);
			String[] zWordNameStr = new String[zList.size()];
			for (int k = 0; k < zList.size(); k++) {
				ThesauriWordReference aThesauriWordReference = zList.get(k);
				ThesauriWord tThesauriWord = wordService
						.findThesauriWord(Integer
								.parseInt(aThesauriWordReference
										.getReferenceWordId()));
				zWordNameStr[k] = tThesauriWord.getWordName();
			}
			aSolrInputDocument.addField("stringIMS_reference_z", zWordNameStr);

			// 类型
			aSolrInputDocument.addField("type", "thesauriWord");
			twIndexList.add(aSolrInputDocument);
		}
		return twIndexList;
	}

	public void submitWordIndex(List list, String type) {
		try {
			if ("gw".equals(type)) {
				List<SolrInputDocument> gwIndexList = buildGeneralWord(list);
				wordServer.add(gwIndexList);
			} else if ("tw".equals(type)) {
				List<SolrInputDocument> twIndexList = buildThesauriWord(list);
				wordServer.add(twIndexList);
			}

			// server.commit(false, false);
		} catch (Exception e) {
			LOG.error("批量创建索引失败.", e);
			e.printStackTrace();
		}
	}

	public void submitBaikeIndex(List<BaikeEntry> list) {
		List<SolrInputDocument> indexList = this.buildBaikeEntry(list);
		try {
			baikeServer.add(indexList);
			// server.commit(false, false);
		} catch (Exception e) {
			LOG.error("批量创建索引失败.", e);
			e.printStackTrace();
		}
	}

	public List<SolrInputDocument> buildBaikeEntry(List<BaikeEntry> list) {
		List<SolrInputDocument> indexList = new ArrayList<SolrInputDocument>();
		SolrInputDocument aSolrInputDocument = null;

		for (int j = 0; j < list.size(); j++) {
			aSolrInputDocument = new SolrInputDocument();
			BaikeEntry aBaikeEntry = list.get(j);

			aSolrInputDocument.addField("id", aBaikeEntry.getId());
			// 不分词
			aSolrInputDocument.addField("stringIS_sid", aBaikeEntry.getSid());
			aSolrInputDocument.addField("stringIS_description_img",
					aBaikeEntry.getDescriptionImg());
			aSolrInputDocument.addField("stringIS_version",
					aBaikeEntry.getVersion());
			aSolrInputDocument.addField("stringIS_ip_address",
					aBaikeEntry.getIpAddress());
			aSolrInputDocument.addField("stringIS_date", aBaikeEntry.getDate());
			aSolrInputDocument.addField("intIS_year", aBaikeEntry.getDate()
					.substring(0, 4));
			aSolrInputDocument.addField("stringIS_author",
					aBaikeEntry.getAuthor());
			aSolrInputDocument.addField("stringIS_title",
					aBaikeEntry.getTitle());

			aSolrInputDocument.addField("stringIS_source",
					aBaikeEntry.getSource());
			aSolrInputDocument.addField("stringIS_basic_text",
					aBaikeEntry.getBasicText());
			// aSolrInputDocument.addField("stringIS_reference_material",
			// aBaikeEntry.getReferenceMaterial());
			aSolrInputDocument.addField("stringIS_relationship",
					aBaikeEntry.getRelationship());

			// 分词(多语种) 目前不需要多语种 先注释掉 用到再放开
/*			aSolrInputDocument.addField("auto_stringITSV_title",
					LangDetectUtils.detectLangsAndWrap(aBaikeEntry.getTitle()));
			aSolrInputDocument.addField("auto_stringITSV_description",
					LangDetectUtils.detectLangsAndWrap(aBaikeEntry
							.getDescription()));
			aSolrInputDocument.addField("auto_stringITM_main_text",
					LangDetectUtils.detectLangsAndWrap(aBaikeEntry
							.getMainText()));*/
			aSolrInputDocument.addField("auto_stringITSV_title",aBaikeEntry.getTitle());
					
			aSolrInputDocument.addField("auto_stringITSV_description",aBaikeEntry.getDescription());
					
			aSolrInputDocument.addField("auto_stringITM_main_text",aBaikeEntry.getMainText());
					
			// 多值
			String photoAlbum = aBaikeEntry.getPhotoAlbum();
			String[] photoAlbumArray = null;
			if (photoAlbum != null) {
				photoAlbumArray = photoAlbum.split("≡");
			}
			aSolrInputDocument.addField("stringIMS_photo_album",
					photoAlbumArray);
			// 相关词（relationship中获得）synonyms#计算机技术∷计算机∷计算机科学≡antonym#秦时明月∷中国人
			String relationship = aBaikeEntry.getRelationship();
			if (relationship != null) {
				String[] relationshipArray = relationship.split("≡");
				List<String> wordList = new ArrayList<String>();
				for (int i = 0; i < relationshipArray.length; i++) {
					if (null != relationshipArray[i]
							&& !"".equals(relationshipArray[i])) {
						String[] wordArray = (relationshipArray[i].split("#")[1])
								.toString().split("∷");
						for (int k = 0; k < wordArray.length; k++) {
							wordList.add(wordArray[k]);
						}
					}
					//
				}
				String[] wordArray = new String[wordList.size()];
				for (int i = 0; i < wordList.size(); i++) {
					wordArray[i] = wordList.get(i);
				}
				// 添加至solr
				aSolrInputDocument.addField("stringIMS_word", wordArray);
			}

			// 类型
			aSolrInputDocument.addField("type", "baike");

			indexList.add(aSolrInputDocument);
		}

		return indexList;
	}

	private SolrInputDocument buildBaikeEntry(BaikeEntry aBaikeEntry) {
		SolrInputDocument aSolrInputDocument = new SolrInputDocument();
		aSolrInputDocument.addField("id", aBaikeEntry.getId());

		// 不分词
		aSolrInputDocument.addField("stringIS_sid", aBaikeEntry.getSid());
		aSolrInputDocument.addField("stringIS_description_img",
				aBaikeEntry.getDescriptionImg());
		aSolrInputDocument.addField("stringIS_version",
				aBaikeEntry.getVersion());
		aSolrInputDocument.addField("stringIS_ip_address",
				aBaikeEntry.getIpAddress());
		aSolrInputDocument.addField("stringIS_date", aBaikeEntry.getDate());
		aSolrInputDocument.addField("intIS_year", aBaikeEntry.getDate()
				.substring(0, 4));
		aSolrInputDocument.addField("stringIS_author", aBaikeEntry.getAuthor());
		aSolrInputDocument.addField("stringIS_title", aBaikeEntry.getTitle());

		aSolrInputDocument.addField("stringIS_source", aBaikeEntry.getSource());
		aSolrInputDocument.addField("stringIS_basic_text",
				aBaikeEntry.getBasicText());
		// aSolrInputDocument.addField("stringIS_reference_material",
		// aBaikeEntry.getReferenceMaterial());
		aSolrInputDocument.addField("stringIS_relationship",
				aBaikeEntry.getRelationship());

		// 分词(多语种)
/*		aSolrInputDocument.addField("auto_stringITSV_title",
				LangDetectUtils.detectLangsAndWrap(aBaikeEntry.getTitle()));
		aSolrInputDocument
				.addField("auto_stringITSV_description", LangDetectUtils
						.detectLangsAndWrap(aBaikeEntry.getDescription()));
		aSolrInputDocument.addField("auto_stringITM_main_text",
				LangDetectUtils.detectLangsAndWrap(aBaikeEntry.getMainText()));*/
		aSolrInputDocument.addField("auto_stringITSV_title",aBaikeEntry.getTitle());
				
		aSolrInputDocument.addField("auto_stringITSV_description", aBaikeEntry.getDescription());
				
		aSolrInputDocument.addField("auto_stringITM_main_text",aBaikeEntry.getMainText());	
		// 多值
		String photoAlbum = aBaikeEntry.getPhotoAlbum();
		String[] photoAlbumArray = null;
		if (photoAlbum != null) {
			photoAlbumArray = photoAlbum.split("≡");
		}
		aSolrInputDocument.addField("stringIMS_photo_album", photoAlbumArray);
		// 相关词（relationship中获得）synonyms#计算机技术∷计算机∷计算机科学≡antonym#秦时明月∷中国人
		String relationship = aBaikeEntry.getRelationship();
		if (relationship != null) {
			String[] relationshipArray = relationship.split("≡");
			List<String> wordList = new ArrayList<String>();
			for (int i = 0; i < relationshipArray.length; i++) {
				if (!"".equals(relationshipArray[i])) {
					String[] wordArray = (relationshipArray[i].split("#")[1])
							.toString().split("∷");
					for (int k = 0; k < wordArray.length; k++) {
						wordList.add(wordArray[k]);
					}
				}
			}
			String[] wordArray = new String[wordList.size()];
			for (int i = 0; i < wordList.size(); i++) {
				wordArray[i] = wordList.get(i);
			}
			// 添加至solr
			aSolrInputDocument.addField("stringIMS_word", wordArray);
		}

		// 类型
		aSolrInputDocument.addField("type", "baike");
		return aSolrInputDocument;
	}

	@Override
	public void submitBaikeIndex(BaikeEntry baikeEntry) {
		SolrInputDocument aSolrInputDocument = buildBaikeEntry(baikeEntry);
		try {
			baikeServer.add(aSolrInputDocument);
			baikeServer.commit(false, false);
		} catch (Exception e) {
			LOG.error("发布索引失败.", e);
			e.printStackTrace();
		}
	}

	@Override
	public void deleteIndexByClassesEn(String classesEn) {
		try {
			server.deleteByQuery("type:" + classesEn);
			server.commit(false, false);
		} catch (Exception e) {
			rollback();
			LOG.error("删除索引失败.", e);
			e.printStackTrace();
		}
	}

	@Override
	public boolean addDynamicData(String classesEn,
			List<Map<String, Object>> dynamicDatas, String createTime,
			String createUserId, String status, String version,
			String classesId, String dataSource) {
		return addDynamicData(classesEn, dynamicDatas, createTime,
				createUserId, status, version, classesId, dataSource, false);
	}

	@Override
	public String addDynamicData(String classesEn,
			Map<String, Object> dynamicData, String createTime,
			String createUserId, String status, String version,
			String classesId, String dataSource) {
		return addDynamicData(classesEn, dynamicData, createTime, createUserId,
				status, version, classesId, dataSource, false);
	}

	@Override
	public boolean editDynamicData(String classesEn,
			Map<String, Object> dynamicData, Map<String, Object> conditions,
			String updateTime, String updateUserId, String status,
			String version) {
		return editDynamicData(classesEn, dynamicData, conditions, updateTime,
				updateUserId, status, version, null, null);
	}

	@Override
	public void editDynamicData(String classesEn,
			List<Map<String, Object>> dynamicDatas, String updateTime,
			String updateUserId, String status, String version) {
		editDynamicData(classesEn, dynamicDatas, updateTime, updateUserId,
				status, version, null, null);
	}

	@Override
	public void editDynamicData(String classesEn,
			Map<String, Object> dynamicData, String updateTime,
			String updateUserId, String status, String version, String id) {
		editDynamicData(classesEn, dynamicData, updateTime, updateUserId,
				status, version, id, null, null);
	}

	@Override
	public void editDynamicDataCreateUser(String classesEn, String id,
			String userId) {
		editDynamicDataCreateUser(classesEn, id, userId, null, null);
	}

	@Override
	public void deleteDynamicData(String classesEn,
			Map<String, Object> dynamicData) {
		deleteDynamicData(classesEn, dynamicData, null, null);
	}

	@Override
	public Map<String, Object> findDynamicData(String classesEn, String id,
			String fields) {
		return findDynamicData(classesEn, id, fields, null, null);
	}

	@Override
	public Map<String, Object> findDynamicData(String classesEn, String id) {
		return findDynamicData(classesEn, id, null, null);
	}

	public List<Map<String, Object>> getDynamicData(String classesEn,
			Map<String, Object> conditions, String orderByField,
			String orderByValue, int pageNumber, int pageSize) {
		return getDynamicData(classesEn, conditions, orderByField,
				orderByValue, pageNumber, pageSize, null, null);
	}

	public List<Map<String, Object>> getDynamicDataList(String classesEn,
			String showField, Map<String, Object> conditions,
			String orderByField, String orderByValue, int pageNumber,
			int pageSize) {
		return getDynamicDataList(classesEn, showField, conditions,
				orderByField, orderByValue, pageNumber, pageSize, null, null);
	}

	@Override
	public List<Map<String, Object>> getDynamicData(String classesEn,
			Map<String, Object> conditions, int pageNumber, int pageSize) {
		return getDynamicData(classesEn, conditions, null, null, pageNumber,
				pageSize, null, null);
	}

	@Override
	public List<Map<String, Object>> getDynamicDataList(String classesEn,
			String showField, Map<String, Object> conditions, int pageNumber,
			int pageSize) {
		return getDynamicDataList(classesEn, showField, conditions, null, null,
				pageNumber, pageSize, null, null);
	}

	@Override
	public Long getDynamicCount(String classesEn, Map<String, Object> conditions) {
		return getDynamicCount(classesEn, conditions, null, null);
	}

	/**
	 * 对content的内容进行转换后，在作为oracle查询的条件字段值。使用\作为oracle的转义字符。<br>
	 * 这种做法也能达到目的，但不是好的做法，比较容易出错，而且代码很那看懂。<br>
	 * "%'" + content + "'% ESCAPE '\' "这种拼接sql实际上是错误的.<br>
	 * "%'" + content + "'% ESCAPE '\\' "这种拼接sql才是正确的<br>
	 * 
	 * @param content
	 * @return
	 */
	private String decodeSpecialCharsWhenLikeUseSlash(String content) {
		// 单引号是oracle字符串的边界,oralce中用2个单引号代表1个单引号
		String afterDecode = content.replaceAll("'", "''");
		// 由于使用了\作为ESCAPE的转义特殊字符,所以需要对该字符进行转义
		// 由于\在java和正则表达式中都是特殊字符,需要进行特殊处理
		// 这里的作用是将"a\a"转成"a\\a"
		afterDecode = afterDecode.replaceAll("\\\\", "\\\\\\\\");
		// 使用转义字符 \,对oracle特殊字符% 进行转义,只作为普通查询字符，不是模糊匹配
		afterDecode = afterDecode.replaceAll("%", "\\\\%");
		// 使用转义字符 \,对oracle特殊字符_ 进行转义,只作为普通查询字符，不是模糊匹配
		// afterDecode = afterDecode.replaceAll("_", "\\\\_");
		return afterDecode;
	}

	@Override
	public Long getDynamicCount(String classesEn, String createUserId,
			String startTime, String endTime) {
		return getDynamicCount(classesEn, createUserId, startTime, endTime,
				null, null);
	}

	@Override
	public void saveDynamicObjectData(String classesEn, String id,
			String relevanceClassesEn, String relevanceId,
			Integer objectPropertyId, String createTime, String createUserId) {
		saveDynamicObjectDataST(classesEn, id, relevanceClassesEn, relevanceId,
				objectPropertyId, createTime, createUserId, null, null, null,
				null);
	}

	@Override
	public void deleteDynamicObjectData(String classesEn, String id,
			Integer objectPropertyId) {
		deleteDynamicObjectData(classesEn, id, objectPropertyId, null, null);
	}

	@Override
	public Long getDynamicObjectDataCount(String classesEn, String sourceId,
			String targetId, Integer objectPropertyId) {
		return getDynamicObjectDataCount(classesEn, sourceId, targetId,
				objectPropertyId, null, null);
	}

	@Override
	public List<Map<String, Object>> getDynamicObjectData(String classesEn,
			String sourceId, String targetId, Integer objectPropertyId,
			int pageNumber, int pageSize) {
		return getDynamicObjectData(classesEn, sourceId, targetId,
				objectPropertyId, pageNumber, pageSize, null, null);
	}

	@Override
	public void submitDynamicData(String classesEn, String submitTime,
			String submitUserId, String id, String shardingDataSourceId,
			String tableName) {
		Map<String, Object> map = findDynamicData(classesEn, id,
				shardingDataSourceId, tableName);
		if (map != null) {
			// 发布至solr
			submitDataForSolr(map, classesEn, shardingDataSourceId, tableName);
		}
	}

	@Override
	public void submitDynamicData(String classesEn, String submitTime,
			String submitUserId, String id) {
		Map<String, Object> map = findDynamicData(classesEn, id);
		if (map != null) {
			// 发布至solr
			submitDataForSolr(map, classesEn, null, null);
		}
	}

	@Override
	public void submitDynamicData(String classesEn, String submitTime,
			String submitUserId) {
		submitDynamicData(classesEn, submitTime, submitUserId, null, null);
	}

	/**
	 * 构建solr数据格式
	 * 
	 * @param data
	 * @param aClasses
	 * @return
	 */
	private SolrInputDocument buildSolrInputDocument(Map<String, Object> data,
			Classes aClasses, String shardingDataSourceId, String tableName) {
		SolrInputDocument sid = new SolrInputDocument();
		try {
			// 查询类对象属性
			List<ObjectProperty> opList = publicService
					.getObjectProperty(aClasses);
			for (int i = 0; i < opList.size(); i++) {

				ObjectProperty aObjectProperty = opList.get(i);
				// 对象属性关联字段
				String relevanceClassFields = aObjectProperty
						.getRelevanceClassFields();
				// 查询对象属性值，需要判断分库分表信息
				List<Map<String, Object>> opDataList = null;
				if (shardingDataSourceId != null
						&& !"".equals(shardingDataSourceId)
						&& tableName != null && !"".equals(tableName)) {
					opDataList = getDynamicObjectData(aClasses.getNameEn(),
							data.get("id").toString(), null,
							aObjectProperty.getId(), 1, Integer.MAX_VALUE,
							shardingDataSourceId, tableName);
				} else {
					opDataList = getDynamicObjectData(aClasses.getNameEn(),
							data.get("id").toString(), null,
							aObjectProperty.getId(), 1, Integer.MAX_VALUE);
				}
				String[] opDataArray = new String[opDataList.size()];

				for (int j = 0; j < opDataList.size(); j++) {
					Map<String, Object> opMap = opDataList.get(j);
					// 查询关联表
					Classes targetClasses = publicService
							.findClasses(aObjectProperty
									.getRelevanceClassesId());
					// 查询关联数据详情，分库分表情况下从opDataList获得target_table_name名称
					Map<String, Object> targetMap = null;
					if (shardingDataSourceId != null
							&& !"".equals(shardingDataSourceId)
							&& tableName != null && !"".equals(tableName)) {
						targetMap = findDynamicData(targetClasses.getNameEn(),
								opMap.get("target_data_id").toString(),
								relevanceClassFields,
								opMap.get("target_sharding_data_source_id")
										.toString(),
								opMap.get("target_table_name").toString());
					} else {
						targetMap = findDynamicData(targetClasses.getNameEn(),
								opMap.get("target_data_id").toString(),
								relevanceClassFields);
					}
					// 关联组合值
					String relevanceData = "op_id∷" + opMap.get("id") + "≡"
							+ "target_class_en∷" + targetClasses.getNameEn()
							+ "≡" + "target_class_zh∷"
							+ targetClasses.getNameZh() + "≡target_id∷"+targetClasses.getId()+"≡";
					if (targetMap != null) {
						Iterator iter = targetMap.entrySet().iterator();
						while (iter.hasNext()) {
							Map.Entry entry = (Map.Entry) iter.next();
							String oldKey = entry.getKey().toString();
							Object oldVal = entry.getValue();
							if(oldVal!=null){
								oldVal = StringUtils.trim(oldVal.toString());
							}
							relevanceData += oldKey + "∷" + oldVal + "≡";
						}
						opDataArray[j] = relevanceData.substring(0,
								relevanceData.length() - 1);
					}
					// 根据op对应字段判断是否需要拆分，分开存储字段
					//
				}
				sid.addField("stringIMS_" + aObjectProperty.getNameEn()
						+ "_data", opDataArray);

			}

			// 分库分表信息
			if (shardingDataSourceId != null
					&& !"".equals(shardingDataSourceId)) {
				sid.addField("stringIS_shardingDataSourceId",
						shardingDataSourceId);
			}
			if (tableName != null && !"".equals(tableName)) {
				sid.addField("stringIS_tableName", tableName);
			}

			// 查询类数据属性（字段）
			List<DataProperty> dpList = publicService.getDataProperty(aClasses);
			sid.addField("stringIS_classEn", aClasses.getNameEn());
			sid.addField("type", aClasses.getNameEn());
			sid.addField("stringIS_classZh", aClasses.getNameZh());
			sid.addField("id", data.get("id").toString());
			if (!"".equals(data.get("create_time").toString())) {
				sid.addField("dateIS_create_time", DateUtils.ConverToDate(data
						.get("create_time").toString()));
			}
			/*
			if (!"".equals(data.get("create_year").toString())) {
				sid.addField("stringIS_create_year", (data
						.get("create_year").toString()));
			}
			*/
			if (!"".equals(data.get("update_time").toString())) {
				sid.addField("dateIS_update_time", DateUtils.ConverToDate(data
						.get("update_time").toString()));
			}
			if (!"".equals(data.get("status").toString())) {
				sid.addField("intIS_status", data
						.get("status").toString());
			}
			if (!"".equals(data.get("create_user_id").toString())) {
				sid.addField("intIS_create_user_id", data
						.get("create_user_id").toString());
			}
			if (!"".equals(data.get("classes_id").toString())) {
				sid.addField("intIS_classes_id", data
						.get("classes_id").toString());
			}
			for (int m = 0; m < dpList.size(); m++) {
				DataProperty aDataProperty = dpList.get(m);
				DataType aDataType = publicService.findDataType(aDataProperty
						.getDataTypeId());
				String multiLanguage = "";
				String dataType = "";
				String solrFieldValue = null;
				String[] solrFieldValueArray = null;

				Object value = data.get(aDataProperty.getNameEn());

				if (aDataType.getSolrType().equals("string_auto")) {
					multiLanguage = "1";
					dataType = "string";
					if (value != null) {
						// solrFieldValue = "en,zh-cn|" + value.toString();
						//solrFieldValue = LangDetectUtils.detectLangsAndWrap(value.toString());
						solrFieldValue = StringUtils.trim(value.toString());
					}
				} else {
					multiLanguage = "0";
					dataType = aDataType.getSolrType();
					if (value != null && !"".equals(value.toString())
							&& !" ".equals(value.toString())) {
						// 判断字段多值情况
						if ("1".equals(aDataProperty.getMultiValued())) {
							// separator
							if (!"".equals(value.toString())) {
								solrFieldValueArray = value.toString().split(
										aDataProperty.getSeparator());
							}
						} else {
							solrFieldValue = StringUtils.trim(value.toString());
						}
					}
				}

				String solrField = FieldPrefixUtils.getDynamicField(dataType,
						null, multiLanguage, aDataProperty.getIndexed(),
						aDataProperty.getMultiValued(),
						aDataProperty.getStored(),
						aDataProperty.getTermVectors(),
						aDataProperty.getRequired());
				if (dataType.equals("date")) {
					if (!"".equals(solrFieldValue)) {
						sid.addField(solrField + aDataProperty.getField(),
								DateUtils.ConverToDate(solrFieldValue));
					} else {
						sid.addField(solrField + aDataProperty.getField(), null);
					}
				} else if (dataType.equals("double")) {
					if (!"".equals(solrFieldValue)
							&& !"null".equals(solrFieldValue)) {
						sid.addField(solrField + aDataProperty.getField(),
								solrFieldValue);
					} else {
						sid.addField(solrField + aDataProperty.getField(), null);
					}
				} else if (dataType.equals("int")) {
					if (!"".equals(solrFieldValue)
							&& !"null".equals(solrFieldValue)
							&& CodeUtils.isNumeric(solrFieldValue)) {
						sid.addField(solrField + aDataProperty.getField(),
								solrFieldValue);
					} else {
						sid.addField(solrField + aDataProperty.getField(), null);
					}
				} else {
					// 判断字段多值情况
					if ("1".equals(aDataProperty.getMultiValued())) {
						sid.addField(solrField + aDataProperty.getField(),
								solrFieldValueArray);
					} else {
						if (!"".equals(solrFieldValue)
								&& (!"en,zh-cn|".equals(solrFieldValue)
										|| !"en|".equals(solrFieldValue) || !"zh-cn|"
											.equals(solrFieldValue))) {
							sid.addField(solrField + aDataProperty.getField(),
									solrFieldValue);
						}
						//
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sid;
	}

	// 发布类数据至solr
	private void submitDataForSolr(Map<String, Object> data, String classesEn,
			String shardingDataSourceId, String tableName) {
		HashMap<String, Object> r = new HashMap<String, Object>();
		// 查询类
		HashMap<String, Object> queryParams = new HashMap<>();
		queryParams.put("=,nameEn", classesEn);
		List<Classes> classesList = publicService.getClasses(queryParams, 1, 1);
		Classes aClasses = null;
		if (classesList.size() > 0) {
			aClasses = classesList.get(0);
		} else {
			return;
		}
		try {
			SolrInputDocument sid = buildSolrInputDocument(data, aClasses,
					shardingDataSourceId, tableName);
			createIndex(sid);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * add索引
	 */
	public synchronized void createIndex(SolrInputDocument sid) {
		try {
			server.add(sid);
			server.commit(false, false);
		} catch (Exception e) {
			LOG.error("单条创建索引失败.", e);
			e.printStackTrace();
		}
	}

	/**
	 * 批量add索引
	 */
	public void createIndex(List<Map<String, Object>> list) {
		try {
			List<SolrInputDocument> sids = new ArrayList<SolrInputDocument>();
			SolrInputDocument aSolrInputDocument = null;
			for (Map<String, Object> map : list) {
				aSolrInputDocument = new SolrInputDocument();
				for (String key : map.keySet()) {
					aSolrInputDocument.addField(key, map.get(key));
				}
				sids.add(aSolrInputDocument);
			}
			server.add(sids);
			// server.commit(false, false);
		} catch (Exception e) {
			LOG.error("批量创建索引失败.", e);
			e.printStackTrace();
		}
	}

	@Override
	public HashMap<String, Object> getDataSchema() {
		if (dataSchema == null || dataSchema.size() == 0) {
			System.out.println(">>> 缓存知识结构开始...");
			saveObjectForCache();
			System.out.println(">>> 缓存知识结构结束...记录总数=" + dataSchema.size());
		}
		return dataSchema;
	}

	@Override
	public void saveObjectForCache() {
		// 清空redis缓存
		dataSchema = new HashMap<String, Object>();

		// 字典类、字典项
		List<Dict> dictList = publicService.getDict();
		dataSchema.put("dictList", dictList);
		for (int i = 0; i < dictList.size(); i++) {
			Dict aDict = dictList.get(i);
			dataSchema.put(aDict.getNameEn(), aDict);
			List<DictItem> dictItemList = publicService.getDictItem(aDict);
			dataSchema.put(aDict.getNameEn() + ".dictItem", dictItemList);
		}
		// 公用数据属性
		List<CommonDataProperty> cdpList = publicService
				.getCommonDataProperty();
		dataSchema.put("commonDpList", cdpList);
		for (int i = 0; i < cdpList.size(); i++) {
			CommonDataProperty aCommonDataProperty = cdpList.get(i);
			dataSchema.put("common.dp." + aCommonDataProperty.getField(),
					aCommonDataProperty);
		}
		// 公共对象属性
		List<CommonObjectProperty> copList = publicService
				.getCommonObjectProperty();
		dataSchema.put("commonOpList", copList);
		for (int i = 0; i < copList.size(); i++) {
			CommonObjectProperty aCommonObjectProperty = copList.get(i);
			dataSchema.put("common.op." + aCommonObjectProperty.getField(),
					aCommonObjectProperty);
		}
		// 类、基础属性、关系属性
		List<Classes> classesList = publicService.getClasses();
		dataSchema.put("classesList", classesList);
		for (int j = 0; j < classesList.size(); j++) {
			Classes aClasses = classesList.get(j);
			dataSchema.put(aClasses.getNameEn(), aClasses);
			List<DataProperty> dpList = publicService.getDataProperty(aClasses);
			List<ObjectProperty> opList = publicService
					.getObjectProperty(aClasses);
			// 存储具体属性
			for (int k = 0; k < dpList.size(); k++) {
				DataProperty aDataProperty = dpList.get(k);
				String solrField = getSolrField(aDataProperty).get("solrField");
				dataSchema.put(
						aClasses.getNameEn() + ".dp."
								+ aDataProperty.getNameEn(), aDataProperty);
				// 正向
				dataSchema.put("field." + aDataProperty.getNameEn(), solrField);
				// 反向
				dataSchema.put("field." + solrField, aDataProperty.getNameEn());
			}
			dataSchema.put(aClasses.getNameEn() + ".dpList", dpList);
			for (int k = 0; k < opList.size(); k++) {
				ObjectProperty aObjectProperty = opList.get(k);
				dataSchema.put(
						aClasses.getNameEn() + ".op."
								+ aObjectProperty.getNameEn(), aObjectProperty);
				// 正向
				dataSchema.put("field." + aObjectProperty.getNameEn(),
						"stringIMS_" + aObjectProperty.getNameEn() + "_data");
				// 反向
				dataSchema.put(
						"field." + "stringIMS_" + aObjectProperty.getNameEn()
								+ "_data", aObjectProperty.getNameEn());
			}
			dataSchema.put(aClasses.getNameEn() + ".opList", opList);
		}
	}

	private HashMap<String, String> getSolrField(DataProperty aDataProperty) {
		HashMap<String, String> r = new HashMap<String, String>();

		String solrField = "";
		DataType aDataType = publicService.findDataType(aDataProperty
				.getDataTypeId());

		String multiLanguage = "";
		String dataType = "";
		if (aDataType.getSolrType().equals("string_auto")) {
			multiLanguage = "1";
			dataType = "string";
		} else {
			multiLanguage = "0";
			dataType = aDataType.getSolrType();
		}
		solrField = FieldPrefixUtils.getDynamicField(dataType, null,
				multiLanguage, aDataProperty.getIndexed(),
				aDataProperty.getMultiValued(), aDataProperty.getStored(),
				aDataProperty.getTermVectors(), aDataProperty.getRequired())
				+ aDataProperty.getNameEn();
		r.put("solrField", solrField);

		return r;
	}

	/**
	 * 删除所有
	 */
	public synchronized void deleteAllIndex() {
		try {
			server.deleteByQuery("*:*");
			server.commit(false, false);
		} catch (Exception e) {
			rollback();
			LOG.error("删除索引失败.", e);
			e.printStackTrace();
		}
	}

	/**
	 * 回滚操作
	 */
	public UpdateResponse rollback() {
		try {
			LOG.error("创建索引异常,数据已回滚.");
			return server.rollback();
		} catch (SolrServerException | IOException e) {
			throw new RuntimeException(e);
		}
	}

	public synchronized void deleteIndex(String[] ids) {
		try {
			if (ids.length > 0) {
				StringBuffer query = new StringBuffer("id:" + ids[0]);
				for (int i = 1; i < ids.length; i++) {
					query.append(" OR  id:" + ids[i]);
				}
				server.deleteByQuery(query.toString());
				server.commit(false, false);
			}

		} catch (Exception e) {
			rollback();
			LOG.error("删除索引失败.", e);
			e.printStackTrace();
		}
	}

	@Override
	public void editClassesDb(String classesEn) {
		// 创建数据库表
		String sql = DBUtils.createTable(dbStyle, repositoryPrefix + "_"
				+ classesEn);
		System.out.println("知识库创建表SQL:" + sql);
		aSQLAdapter = new SQLAdapter();
		aSQLAdapter.setSql(sql);
		int dm = dynamicMapper.executeSQL(aSQLAdapter);
		System.out.println("执行创建表sql返回结果集:" + dm);
		// 更新dp字段
		if (dataSchema == null || dataSchema.size() == 0) {
			saveObjectForCache();
		}
		List<DataProperty> dpList = (List<DataProperty>) dataSchema
				.get(classesEn + ".dpList");

		for (int i = 0; i < dpList.size(); i++) {
			DataProperty aDataProperty = dpList.get(i);
			DataType aDataType = publicService.findDataType(aDataProperty
					.getDataTypeId());
			HashMap<String, String> fields = new HashMap<String, String>();
			fields.put(aDataProperty.getNameEn(), aDataType.getFieldType()
					+ "/" + aDataProperty.getFieldLength().intValue());
			// 新增字段
			sql = DBUtils.updateName(dbStyle, repositoryPrefix + "_"
					+ classesEn, "add", fields);
			System.out.println("新增字段SQL:" + sql);
			aSQLAdapter = new SQLAdapter();
			aSQLAdapter.setSql(sql);
			int dpDM = dynamicMapper.executeSQL(aSQLAdapter);
			System.out.println("执行更新表sql返回结果集:" + dpDM);
		}

		// 创建关系表
		List<ObjectProperty> opList = (List<ObjectProperty>) dataSchema
				.get(classesEn + ".opList");

		for (int i = 0; i < opList.size(); i++) {
			ObjectProperty aObjectProperty = opList.get(i);
			Classes aClasses = publicService.findClasses(aObjectProperty
					.getClassesId());
			sql = DBUtils.createOpTable(dbStyle, repositoryPrefix + "_"
					+ aClasses.getNameEn() + "_" + aObjectProperty.getNameEn());
			System.out.println("创建关系表SQL=" + sql);
			aSQLAdapter = new SQLAdapter();
			aSQLAdapter.setSql(sql);
			int opDM = dynamicMapper.executeSQL(aSQLAdapter);
			System.out.println("执行op表sql返回结果集:" + opDM);
		}

	}

	@Override
	public List<HashMap<String, String>> getSystemList() {
		List<HashMap<String, String>> r = new ArrayList<HashMap<String, String>>();
		HashMap<String, String> map = null;
		// 大数据仓储（导入、导出）
		map = new HashMap<String, String>();
		map.put("systemZh", "大数据仓储");
		map.put("systemEn", "store");
		r.add(map);
		// 知识词表（导入、导出、发布）
		map = new HashMap<String, String>();
		map.put("systemZh", "知识词表");
		map.put("systemEn", "word");
		r.add(map);
		// 自然语言处理（自动标引）
		map = new HashMap<String, String>();
		map.put("systemZh", "自然语言处理");
		map.put("systemEn", "nlp");
		r.add(map);
		// 统一检索（发布索引）
		map = new HashMap<String, String>();
		map.put("systemZh", "统一检索");
		map.put("systemEn", "search");
		r.add(map);
		// 统一身份认证（导入、导出）
		map = new HashMap<String, String>();
		map.put("systemZh", "统一身份认证");
		map.put("systemEn", "uias");
		r.add(map);
		// 互联网采集（数据抓取）
		map = new HashMap<String, String>();
		map.put("systemZh", "互联网采集");
		map.put("systemEn", "spider");
		r.add(map);
		// 知识百科（导入、导出、发布索引）
		map = new HashMap<String, String>();
		map.put("systemZh", "知识百科");
		map.put("systemEn", "baike");
		r.add(map);
		return r;
	}

	@Override
	public List<HashMap<String, String>> getModuleList(String systemEn) {
		List<HashMap<String, String>> r = new ArrayList<HashMap<String, String>>();
		HashMap<String, String> map = null;
		if ("search".equals(systemEn)) {
			map = new HashMap<String, String>();
			map.put("moduleZh", "发布索引");
			map.put("moduleEn", "submitIndex");
			r.add(map);
		} else if ("store".equals(systemEn)) {
			map = new HashMap<String, String>();
			map.put("moduleZh", "导入");
			map.put("moduleEn", "import");
			r.add(map);
			map = new HashMap<String, String>();
			map.put("moduleZh", "导出");
			map.put("moduleEn", "export");
			r.add(map);
		} else if ("word".equals(systemEn)) {
			map = new HashMap<String, String>();
			map.put("moduleZh", "导入");
			map.put("moduleEn", "import");
			r.add(map);
			map = new HashMap<String, String>();
			map.put("moduleZh", "导出");
			map.put("moduleEn", "export");
			r.add(map);
			map = new HashMap<String, String>();
			map.put("moduleZh", "发布索引");
			map.put("moduleEn", "submitIndex");
			r.add(map);
		} else if ("nlp".equals(systemEn)) {
			map = new HashMap<String, String>();
			map.put("moduleZh", "自动标引");
			map.put("moduleEn", "autoIndexing");
			r.add(map);
		} else if ("uias".equals(systemEn)) {
			map = new HashMap<String, String>();
			map.put("moduleZh", "导入");
			map.put("moduleEn", "import");
			r.add(map);
			map = new HashMap<String, String>();
			map.put("moduleZh", "导出");
			map.put("moduleEn", "export");
			r.add(map);
		} else if ("spider".equals(systemEn)) {
			map = new HashMap<String, String>();
			map.put("moduleZh", "数据抓取");
			map.put("moduleEn", "dataCrawling");
			r.add(map);
		} else if ("baike".equals(systemEn)) {
			map = new HashMap<String, String>();
			map.put("moduleZh", "导入");
			map.put("moduleEn", "import");
			r.add(map);
			map = new HashMap<String, String>();
			map.put("moduleZh", "导出");
			map.put("moduleEn", "export");
			r.add(map);
			map = new HashMap<String, String>();
			map.put("moduleZh", "发布索引");
			map.put("moduleEn", "submitIndex");
			r.add(map);
		}
		return r;
	}

	@Override
	public List<HashMap<String, Object>> getTaskList(String systemEn,
			String moduleEn) {
		List<HashMap<String, Object>> r = new ArrayList<HashMap<String, Object>>();
		HashMap<String, Object> map = null;
		// 统一检索子系统-发布索引
		if ("search".equals(systemEn) && "submitIndex".equals(moduleEn)) {
			HashMap<String, Object> queryParams = new HashMap<String, Object>();
			queryParams.put("=,status", 1);
			queryParams.put("^,create_time", "desc");
			Integer dataSubmitCount = publicService.getDataSubmitCount(queryParams);
			List<DataSubmit> list = publicService.getDataSubmit(queryParams, 1,
					dataSubmitCount);
			for (int i = 0; i < list.size(); i++) {
				DataSubmit aDataSubmit = list.get(i);
				map = new HashMap<String, Object>();
				map.put("taskName", aDataSubmit.getName());
				map.put("taskValue",
						"search#submitIndex#" + aDataSubmit.getId());
				r.add(map);
			}
		} else if ("word".equals(systemEn) && "submitIndex".equals(moduleEn)) {
			map = new HashMap<String, Object>();
			map.put("taskName", "普通词表和叙词表");
			map.put("taskValue", "word#submitIndex#0");
			r.add(map);
		} else if ("baike".equals(systemEn) && "submitIndex".equals(moduleEn)) {
			map = new HashMap<String, Object>();
			map.put("taskName", "百科词条");
			map.put("taskValue", "baike#submitIndex#0");
			r.add(map);
		} else if ("store".equals(systemEn)) {// 大数据仓储
			if ("import".equals(moduleEn)) {// 导入
				Wrapper<DataHandling> arg0 = new Wrapper<DataHandling>() {
					@Override
					public String getSqlSegment() {
						return " WHERE SYSTEM_NAME='store' AND TYPE='0' ORDER BY CREATE_TIME DESC";
					}
				};
				List<DataHandling> selectList = dataHandlingService
						.selectList(arg0);
				for (int i = 0; i < selectList.size(); i++) {
					DataHandling dataHandlingImport = selectList.get(i);
					map = new HashMap<String, Object>();
					map.put("taskName", dataHandlingImport.getName());
					map.put("taskValue",
							"store#import#" + dataHandlingImport.getId());
					r.add(map);
				}
			} else if ("export".equals(moduleEn)) {// 导出
				Wrapper<DataHandling> arg0 = new Wrapper<DataHandling>() {
					@Override
					public String getSqlSegment() {
						return " WHERE SYSTEM_NAME='store' AND TYPE='1' ORDER BY CREATE_TIME DESC";
					}
				};
				List<DataHandling> selectList = dataHandlingService
						.selectList(arg0);
				for (int i = 0; i < selectList.size(); i++) {
					DataHandling dataHandlingImport = selectList.get(i);
					map = new HashMap<String, Object>();
					map.put("taskName", dataHandlingImport.getName());
					map.put("taskValue",
							"store#export#" + dataHandlingImport.getId());
					r.add(map);
				}
			}

		}
		return r;
	}

	@Override
	public void submitIndexingIndex(long id, String title, String keyword,
			String summary, String text, String extend1, String extend2,
			String extend3) {
		SolrInputDocument aSolrInputDocument = buildIndexingSolrDocument(id,
				title, keyword, summary, text, extend1, extend2, extend3);
		try {
			indexingServer.add(aSolrInputDocument);
			indexingServer.commit(false, false);
		} catch (Exception e) {
		}
	}

	public SolrInputDocument buildIndexingSolrDocument(long id, String title,
			String keyword, String summary, String text, String extend1,
			String extend2, String extend3) {
		SolrInputDocument aSolrInputDocument = new SolrInputDocument();
		aSolrInputDocument.addField("id", id);
		if (title != null && !"".equals(title)) {
			aSolrInputDocument.addField("auto_stringITSV_title", title);
		}
		if (keyword != null) {
			aSolrInputDocument
					.addField("stringIMS_keyword", keyword.split(","));
		}
		if (summary != null && !"".equals(summary)) {
			aSolrInputDocument.addField("auto_stringITSV_summary", summary);
		}
		if (text != null && !"".equals(text)) {
			aSolrInputDocument.addField("auto_stringITSV_text", text);
		}
		if (extend1 != null && !"".equals(extend1)) {
			aSolrInputDocument.addField("auto_stringITSV_extend1", extend1);
		}
		if (extend2 != null && !"".equals(extend2)) {
			aSolrInputDocument.addField("auto_stringITSV_extend2", extend2);
		}
		if (extend3 != null && !"".equals(extend3)) {
			aSolrInputDocument.addField("auto_stringITSV_extend3", extend3);
		}
		// 类型
		aSolrInputDocument.addField("type", "indexing");
		return aSolrInputDocument;
	}

	@Override
	public void submitIndexingIndex(List<Map<String, String>> list) {
		List<SolrInputDocument> buildIndexingEntry = buildIndexingEntry(list);
		try {
			System.out.println("开始");
			indexingServer.add(buildIndexingEntry);
			System.out.println(buildIndexingEntry.size());
			indexingServer.commit(false, false);
			System.out.println("结束");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public List<SolrInputDocument> buildIndexingEntry(
			List<Map<String, String>> list) {
		List<SolrInputDocument> indexList = new ArrayList<SolrInputDocument>();
		SolrInputDocument aSolrInputDocument = null;

		for (int j = 0; j < list.size(); j++) {
			aSolrInputDocument = new SolrInputDocument();
			Map<String, String> map = list.get(j);

			aSolrInputDocument.addField("id", map.get("id"));
			aSolrInputDocument.addField("auto_stringITSV_title",
					map.get("title"));
			if (map.get("keyword") != null) {
				aSolrInputDocument.addField("stringIMS_keyword",
						map.get("keyword").split(","));
			}
			aSolrInputDocument.addField("auto_stringITSV_summary",
					map.get("summary"));
			aSolrInputDocument.addField("auto_stringITSV_text", map.get("text"));
			aSolrInputDocument.addField("auto_stringITSV_extend1",
					map.get("extend1"));
			aSolrInputDocument.addField("auto_stringITSV_extend2",
					map.get("extend2"));
			aSolrInputDocument.addField("auto_stringITSV_extend3",
					map.get("extend3"));
			// 类型
			aSolrInputDocument.addField("type", "indexing");
			indexList.add(aSolrInputDocument);
		}

		return indexList;
	}

	@Override
	public synchronized void deleteAllIndexingWeight() {
		try {
			indexingServer.deleteByQuery("*:*");
			indexingServer.commit(false, false);
		} catch (Exception e) {
			rollback();
			LOG.error("删除索引失败.", e);
			e.printStackTrace();
		}
	}

	@Override
	public void addDynamicDataVersion(String classesEn,
			Map<String, Object> dynamicData, String updateTime,
			String updateUserId, String status, String version,
			String classesId, String dataSource, String sourceDataId) {
		User aUser = publicService.findUser(Integer.parseInt(updateUserId));

		Document document = new Document();

		String id = String.valueOf(aIdWorker.nextId());
		document.put("source_data_id", sourceDataId);
		document.put("id", id);
		if (null != updateTime && !"".equals(updateTime)) {
			document.put("update_time", updateTime);
		}
		document.put("update_user_id", updateUserId);
		document.put("status", status);
		document.put("version", version);
		document.put("classes_id", classesId);
		document.put("data_source", dataSource);
		if (aUser != null) {
			document.put("update_org_id", aUser.getDepartmentId() + "");
		}
		Iterator iter = dynamicData.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry entry = (Map.Entry) iter.next();
			Object field = entry.getKey();
			Object value = entry.getValue();
			document.put(field.toString(), value == null?null:UnicodeConverter.filterUnicode(String.valueOf(value)));
		}
		MongoClientUtils.insertOne(aMongoDatabaseVersion, repositoryPrefix
				+ "." + classesEn, document);
	}

	@Override
	public List<Map<String, Object>> getDynamicDataVersion(String classesEn,
			String sourceDataId, Map<String, Object> conditions,
			int pageNumber, int pageSize) {
		List<Map<String, Object>> r = new ArrayList<Map<String, Object>>();
		// 查询mongodb
		conditions.put("source_data_id", sourceDataId);
		MongoCursor<Document> aMongoCursor = MongoClientUtils.findByPage(
				aMongoDatabaseVersion, repositoryPrefix + "." + classesEn,
				conditions, "update_time", "desc", pageNumber, pageSize);
		while (aMongoCursor.hasNext()) {
			Document _doc = (Document) aMongoCursor.next();
			// System.out.println(_doc.toString());
			r.add(_doc);
		}
		return r;

	}

	@Override
	public Long getDynamicDataVersionCount(String classesEn,
			String sourceDataId, Map<String, Object> conditions) {
		conditions.put("source_data_id", sourceDataId);
		return MongoClientUtils.findByCount(aMongoDatabaseVersion,
				repositoryPrefix + "." + classesEn, conditions);
	}

	@Override
	public Map<String, Object> findDynamicDataVersion(String classesEn,
			String id) {
		Document aDocument = MongoClientUtils.find(aMongoDatabaseVersion,
				repositoryPrefix + "." + classesEn, id);
		return aDocument;
	}

	@Override
	public List<Map<String, Object>> getDynamicData(String classesEn,
			String id, int pageSize) {
		return getDynamicData(classesEn, id, pageSize, null, null);
	}

	/**
	 * 替换Solr表达式
	 * 
	 * @param queryStr
	 * @return
	 */
	private String replaceSolrQuery(String queryStr) {
		String r = queryStr;
		Pattern p = Pattern.compile("\\$(\\w+(\\d+)?):", Pattern.DOTALL);
		String res_str = r.replaceAll("AND|OR|NOT|\\(|\\)", "≡");
		String[] res_str_arr = res_str.split("≡");
		for (String x : res_str_arr) {
			Matcher ps_mac = p.matcher(x);
			if (ps_mac.find()) {
				String head = ps_mac.group(1);
				String head_str = replaceSolrField(head);
				String value_str = x.split(head)[1].substring(1);
				String newChar = head_str
						+ ":"
						+ replaceSolrFieldValue(StringUtils.trim(head),
								StringUtils.trim(value_str));
				r = r.replace(StringUtils.trim(x), newChar);
			}

		}
		//System.out.println(r);
		return r;
	}

	private String replaceSolrField(String key) {
		if (key.equals("id") || key.equals("type")) {
			return key;
		} else if (key.equals("stringIS_classEn")) {
			return "classEn";
		} else if (key.equals("classEn")) {
			return "stringIS_classEn";
		} else if (key.equals("stringIS_classZh")) {
			return "classZh";
		} else if (key.equals("classZh")) {
			return "stringIS_classZh";
		} else if (key.startsWith("op_")) {
			return "stringIMS_" + key + "_data";
		} else if (key.startsWith("stringIMS_op_") && key.endsWith("_data")) {
			return key.replaceAll("stringIMS_", "").replaceAll("_data", "");
		} else {
			return (String) getDataSchema().get("field." + key);
		}
	}

	/**
	 * 替换字段值
	 * 
	 * @param value
	 * @return
	 */
	private String replaceSolrFieldValue(String field, String value) {
		if (replaceSolrField(field).startsWith("auto_")) {
			// ClientUtils.escapeQueryChars(value)
			return LangDetectUtils.detectLangAndWrap(value, true);
		} else {
			return value;
		}
	}

	@Override
	public void deleteIndexByCondition(String queryStr) {
		try {
			server.deleteByQuery(replaceSolrQuery(queryStr));
			server.commit(false, false);
		} catch (Exception e) {
			rollback();
			LOG.error("删除索引失败.", e);
			e.printStackTrace();
		}
	}

	@Override
	public void deleteBaikeIndexByCondition(String queryStr) {
		try {
			baikeServer.deleteByQuery(queryStr);
			baikeServer.commit(false, false);
		} catch (Exception e) {
			rollback();
			LOG.error("删除索引失败.", e);
			e.printStackTrace();
		}
	}

	@Override
	public void deleteAllBaikeIndex() {
		try {
			baikeServer.deleteByQuery("*:*");
			baikeServer.commit(false, false);
		} catch (Exception e) {
			rollback();
			LOG.error("删除索引失败.", e);
			e.printStackTrace();
		}
	}

	@Override
	public void deleteWordIndexByCondition(String queryStr) {
		try {
			wordServer.deleteByQuery(queryStr);
			wordServer.commit(false, false);
		} catch (Exception e) {
			rollback();
			LOG.error("删除索引失败.", e);
			e.printStackTrace();
		}
	}

	@Override
	public void deleteAllWordIndex() {
		try {
			wordServer.deleteByQuery("*:*");
			wordServer.commit(false, false);
		} catch (Exception e) {
			rollback();
			LOG.error("删除索引失败.", e);
			e.printStackTrace();
		}
	}

	@Override
	public void deleteKwIndexByCondition(String queryStr) {
		try {
			kwServer.deleteByQuery(queryStr);
			kwServer.commit(false, false);
		} catch (Exception e) {
			rollback();
			LOG.error("删除索引失败.", e);
			e.printStackTrace();
		}
	}

	@Override
	public void deleteAllKwIndex() {
		try {
			kwServer.deleteByQuery("*:*");
			kwServer.commit(false, false);
		} catch (Exception e) {
			rollback();
			LOG.error("删除索引失败.", e);
			e.printStackTrace();
		}
	}

	@Override
	public void deleteIndexWeightIndexByCondition(String queryStr) {
		try {
			indexingServer.deleteByQuery(queryStr);
			indexingServer.commit(false, false);
		} catch (Exception e) {
			rollback();
			LOG.error("删除索引失败.", e);
			e.printStackTrace();
		}
	}

	@Override
	public void deleteAllIndexWeightIndex() {
		try {
			indexingServer.deleteByQuery("*:*");
			indexingServer.commit(false, false);
		} catch (Exception e) {
			rollback();
			LOG.error("删除索引失败.", e);
			e.printStackTrace();
		}
	}

	@Override
	public void submitThesauriWordIndex(String thesauriWordId) {
		SolrInputDocument aSolrInputDocument = new SolrInputDocument();
		ThesauriWord aThesauriWord = wordService.findThesauriWord(Integer
				.parseInt(thesauriWordId));
		// System.out.println("叙词表：" + aThesauriWord.getWordName());
		aSolrInputDocument.addField("id", "tw_" + aThesauriWord.getId());
		aSolrInputDocument.addField("stringIS_word_name", aThesauriWord
				.getWordName().toLowerCase());
		aSolrInputDocument.addField("stringIS_is_top_term",
				aThesauriWord.getIsTopTerm());
		aSolrInputDocument.addField("stringIS_word_pinyin",
				aThesauriWord.getWordPinyin());
		if (aThesauriWord.getWordEnglish() != null) {
			aSolrInputDocument.addField("stringIS_word_english", aThesauriWord
					.getWordEnglish().toLowerCase());
		} else {
			aSolrInputDocument.addField("stringIS_word_english",
					aThesauriWord.getWordEnglish());
		}

		aSolrInputDocument.addField("stringITS_usage_note",
				aThesauriWord.getUsageNote());
		aSolrInputDocument.addField("stringITS_scope_note",
				aThesauriWord.getScopeNote());
		aSolrInputDocument.addField("stringITS_historical_note",
				aThesauriWord.getHistoricalNote());
		if (null != aThesauriWord.getWordPid()
				&& !"".equals(aThesauriWord.getWordPid())) {
			aSolrInputDocument.addField("stringIS_word_pid", "tw_"
					+ aThesauriWord.getWordPid());
		}
		// 范畴
		String[] thesauriWordCategoryArray = null;
		String[] wordCategorySid = null;
		String[] wordCategoryName = null;
		String wordCategoryInfo = "";
		if (null != aThesauriWord.getThesauriWordCategoryIds()
				&& !"".equals(aThesauriWord.getThesauriWordCategoryIds())
				&& aThesauriWord.getThesauriWordCategoryIds().contains(";")) {
			thesauriWordCategoryArray = aThesauriWord
					.getThesauriWordCategoryIds().split(";");
			wordCategorySid = new String[thesauriWordCategoryArray.length];
			wordCategoryName = new String[thesauriWordCategoryArray.length];

			for (int k = 0; k < thesauriWordCategoryArray.length; k++) {
				if (thesauriWordCategoryArray[k] != null
						&& !"".equals(thesauriWordCategoryArray[k])) {
					HashMap<String, Object> queryParams = new HashMap<String, Object>();
					queryParams.put("=,categorySid",
							thesauriWordCategoryArray[k]);
					List<ThesauriWordCategory> thesauriWordCategoryList = wordService
							.getThesauriWordCategory(queryParams, 1, 1);
					if (thesauriWordCategoryList.size() > 0) {
						wordCategorySid[k] = thesauriWordCategoryList.get(0)
								.getCategorySid();
						wordCategoryName[k] = thesauriWordCategoryList.get(0)
								.getCategoryName();
						wordCategoryInfo += thesauriWordCategoryList.get(0)
								.getCategorySid()
								+ "∷"
								+ thesauriWordCategoryList.get(0)
										.getCategoryName() + "≡";
					}

				}
			}
		}

		// 多值
		aSolrInputDocument.addField("stringIMS_category_sid", wordCategorySid);
		aSolrInputDocument
				.addField("stringIMS_category_name", wordCategoryName);
		aSolrInputDocument.addField("stringIS_category_info", wordCategoryInfo);

		// 叙词表关系
		HashMap<String, Object> yQueryParams = new HashMap<String, Object>();
		yQueryParams.put("=,thesauriWordId", aThesauriWord.getId());
		yQueryParams.put("=,referenceRelationLabel", "Y");
		List<ThesauriWordReference> yList = wordService
				.getThesauriWordReference(yQueryParams, 1, Integer.MAX_VALUE);
		String[] yWordNameStr = new String[yList.size()];
		for (int k = 0; k < yList.size(); k++) {
			ThesauriWordReference aThesauriWordReference = yList.get(k);
			ThesauriWord tThesauriWord = wordService.findThesauriWord(Integer
					.parseInt(aThesauriWordReference.getReferenceWordId()));
			yWordNameStr[k] = tThesauriWord.getWordName();
		}
		aSolrInputDocument.addField("stringIMS_reference_y", yWordNameStr);

		HashMap<String, Object> dQueryParams = new HashMap<String, Object>();
		dQueryParams.put("=,thesauriWordId", aThesauriWord.getId());
		dQueryParams.put("=,referenceRelationLabel", "D");
		List<ThesauriWordReference> dList = wordService
				.getThesauriWordReference(dQueryParams, 1, Integer.MAX_VALUE);
		String[] dWordNameStr = new String[dList.size()];
		for (int k = 0; k < dList.size(); k++) {
			ThesauriWordReference aThesauriWordReference = dList.get(k);
			ThesauriWord tThesauriWord = wordService.findThesauriWord(Integer
					.parseInt(aThesauriWordReference.getReferenceWordId()));
			dWordNameStr[k] = tThesauriWord.getWordName();
		}
		aSolrInputDocument.addField("stringIMS_reference_d", dWordNameStr);

		HashMap<String, Object> sQueryParams = new HashMap<String, Object>();
		sQueryParams.put("=,thesauriWordId", aThesauriWord.getId());
		sQueryParams.put("=,referenceRelationLabel", "S");
		List<ThesauriWordReference> sList = wordService
				.getThesauriWordReference(sQueryParams, 1, Integer.MAX_VALUE);
		String[] sWordNameStr = new String[sList.size()];
		for (int k = 0; k < sList.size(); k++) {
			ThesauriWordReference aThesauriWordReference = sList.get(k);
			ThesauriWord tThesauriWord = wordService.findThesauriWord(Integer
					.parseInt(aThesauriWordReference.getReferenceWordId()));
			sWordNameStr[k] = tThesauriWord.getWordName();
		}
		aSolrInputDocument.addField("stringIMS_reference_s", sWordNameStr);

		HashMap<String, Object> fQueryParams = new HashMap<String, Object>();
		fQueryParams.put("=,thesauriWordId", aThesauriWord.getId());
		fQueryParams.put("=,referenceRelationLabel", "F");
		List<ThesauriWordReference> fList = wordService
				.getThesauriWordReference(fQueryParams, 1, Integer.MAX_VALUE);
		String[] fWordNameStr = new String[fList.size()];
		for (int k = 0; k < fList.size(); k++) {
			ThesauriWordReference aThesauriWordReference = fList.get(k);
			ThesauriWord tThesauriWord = wordService.findThesauriWord(Integer
					.parseInt(aThesauriWordReference.getReferenceWordId()));
			fWordNameStr[k] = tThesauriWord.getWordName();
		}
		aSolrInputDocument.addField("stringIMS_reference_f", fWordNameStr);

		HashMap<String, Object> cQueryParams = new HashMap<String, Object>();
		cQueryParams.put("=,thesauriWordId", aThesauriWord.getId());
		cQueryParams.put("=,referenceRelationLabel", "C");
		List<ThesauriWordReference> cList = wordService
				.getThesauriWordReference(cQueryParams, 1, Integer.MAX_VALUE);
		String[] cWordNameStr = new String[cList.size()];
		for (int k = 0; k < cList.size(); k++) {
			ThesauriWordReference aThesauriWordReference = cList.get(k);
			ThesauriWord tThesauriWord = wordService.findThesauriWord(Integer
					.parseInt(aThesauriWordReference.getReferenceWordId()));
			cWordNameStr[k] = tThesauriWord.getWordName();
		}
		aSolrInputDocument.addField("stringIMS_reference_c", cWordNameStr);

		HashMap<String, Object> zQueryParams = new HashMap<String, Object>();
		zQueryParams.put("=,thesauriWordId", aThesauriWord.getId());
		zQueryParams.put("=,referenceRelationLabel", "Z");
		List<ThesauriWordReference> zList = wordService
				.getThesauriWordReference(zQueryParams, 1, Integer.MAX_VALUE);
		String[] zWordNameStr = new String[zList.size()];
		for (int k = 0; k < zList.size(); k++) {
			ThesauriWordReference aThesauriWordReference = zList.get(k);
			ThesauriWord tThesauriWord = wordService.findThesauriWord(Integer
					.parseInt(aThesauriWordReference.getReferenceWordId()));
			zWordNameStr[k] = tThesauriWord.getWordName();
		}
		aSolrInputDocument.addField("stringIMS_reference_z", zWordNameStr);

		// 类型
		aSolrInputDocument.addField("type", "thesauriWord");
		List<SolrInputDocument> twIndexList = new ArrayList<SolrInputDocument>();
		twIndexList.add(aSolrInputDocument);
		try {
			wordServer.add(twIndexList);
		} catch (SolrServerException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void submitGeneralWordIndex(String generalWordId) {
		List<SolrInputDocument> gwIndexList = new ArrayList<SolrInputDocument>();
		SolrInputDocument aSolrInputDocument = new SolrInputDocument();
		GeneralWord aGeneralWord = wordService.findGeneralWord(Integer
				.parseInt(generalWordId));
		aSolrInputDocument.addField("id", "gw_" + aGeneralWord.getId());
		aSolrInputDocument.addField("stringIS_word_name", aGeneralWord
				.getWordName().toLowerCase());
		aSolrInputDocument.addField("stringIS_word_pinyin",
				aGeneralWord.getWordPinyin());
		if (aGeneralWord.getWordEnglish() != null) {
			aSolrInputDocument.addField("stringIS_word_english", aGeneralWord
					.getWordEnglish().toLowerCase());
		} else {
			aSolrInputDocument.addField("stringIS_word_english",
					aGeneralWord.getWordEnglish());
		}

		aSolrInputDocument.addField("stringIS_word_initial",
				aGeneralWord.getWordInitial());
		aSolrInputDocument.addField("stringITS_word_scope_note",
				aGeneralWord.getWordScopeNote());
		// 分类信息
		GeneralWordCategory aGeneralWordCategory = wordService
				.findGeneralWordCategory(aGeneralWord
						.getGeneralWordCategoryId());
		if (aGeneralWordCategory != null) {
			aSolrInputDocument.addField("stringIS_category_name",
					aGeneralWordCategory.getCategoryName());
			aSolrInputDocument.addField("stringIS_category_sid",
					aGeneralWordCategory.getCategorySid());
		}
		// 类型
		aSolrInputDocument.addField("type", "generalWord");
		gwIndexList.add(aSolrInputDocument);
		try {
			wordServer.add(gwIndexList);
		} catch (SolrServerException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	@Override
	public void buildShardingRepositoryTable(String classesEn,
			String repositoryDataSourceId) {

		// 查询知识库-数据源关联表
		ShardingRepositoryDataSource aShardingRepositoryDataSource = publicService
				.findShardingRepositoryDataSource(Integer
						.parseInt(repositoryDataSourceId));
		// 数据源
		ShardingDataSource aShardingDataSource = null;
		// 分表个数
		int tableNumber = aShardingRepositoryDataSource.getShardingTableCount();
		if (aShardingRepositoryDataSource != null) {
			aShardingDataSource = publicService
					.findShardingDataSource(aShardingRepositoryDataSource
							.getShardingDataSourceId());
		}
		// 根据数据源，创建数据库表，具体表个数与配置个数相关 sql
		for (int i = 0; i < tableNumber; i++) {
			String sql = DBUtils.createTable(dbStyle,
					aShardingDataSource.getNameEn() + "_"
							+ aShardingRepositoryDataSource.getClassesEn()
							+ "_t" + (i + 1));
			System.out.println("知识库分库分表-创建表SQL:" + sql);

			// 执行sql语句
			Connection conn = null;
			PreparedStatement ps = null;
			ResultSet rs = null;

			try {
				conn = DriverManager.getConnection(
						aShardingDataSource.getDbUrl(),
						aShardingDataSource.getDbUser(),
						aShardingDataSource.getDbPassword());

				ps = conn.prepareStatement(sql);
				ps.execute(sql);

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				// 关闭
				if (rs != null)
					try {
						rs.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				if (ps != null)
					try {
						ps.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				if (conn != null)
					try {
						conn.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				rs = null;
				ps = null;
				conn = null;
			}

			// 插入ShardingRepositoryCount表记录
			ShardingRepositoryCount aShardingRepositoryCount = new ShardingRepositoryCount();
			aShardingRepositoryCount.setClassesEn(classesEn);
			aShardingRepositoryCount.setDataCount(0);
			aShardingRepositoryCount
					.setShardingDataSourceId(aShardingRepositoryDataSource
							.getShardingDataSourceId());
			aShardingRepositoryCount.setTableName(aShardingDataSource
					.getNameEn()
					+ "_"
					+ aShardingRepositoryDataSource.getClassesEn()
					+ "_t"
					+ (i + 1));
			baseService.saveShardingRepositoryCount(aShardingRepositoryCount);
		}
		//
	}

	@Override
	public String addDynamicData(String classesEn,
			Map<String, Object> dynamicData, String createTime,
			String createUserId, String status, String version,
			String classesId, String dataSource, boolean sharding) {
		return addDynamicData(classesEn, dynamicData, createTime, createUserId,
				status, version, classesId, dataSource, sharding, null, null);
	}

	// 分库分表插入数据SQL
	private String shardingInsertSQL(User user,
			Map<String, Object> dynamicData, String createTime,
			String createUserId, String status, String version,
			String classesId, String dataSource,
			ShardingDataSource shardingDataSource, String tableName) {
		String id = String.valueOf(aIdWorker.nextId());

		// 执行sql语句
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;

		try {
			conn = DriverManager.getConnection(shardingDataSource.getDbUrl(),
					shardingDataSource.getDbUser(),
					shardingDataSource.getDbPassword());

			String sql = "";

			///Object[] parms = new Object[9 + dynamicData.size()];
			Object[] parms = new Object[8 + dynamicData.size()];

			sql += " insert into " + tableName + "( ";

			// 通用字段
			//sql += " id,create_time,create_user_id, status, version, classes_id, data_source,create_org_id,create_year,";
			sql += " id,create_time,create_user_id, status, version, classes_id, data_source,create_org_id,";

			// 自定义字段
			Iterator iter = dynamicData.entrySet().iterator();
			int number = 8;
			while (iter.hasNext()) {
				number++;
				Map.Entry entry = (Map.Entry) iter.next();
				Object field = entry.getKey();
				Object value = entry.getValue();
				sql += field + ",";
			}

			if (dynamicData.size() > 0) {
				sql = sql.substring(0, sql.length() - 1);
			}

			String sqlValues = "";
			for (int k = 0; k < parms.length; k++) {
				sqlValues += "?,";
			}
			if (parms.length > 0) {
				sqlValues = sqlValues.substring(0, sqlValues.length() - 1);
			}

			sql += " )  values ( " + sqlValues + " ) ";
			// System.out.println("分库分表单条执行sql=" + sql);

			ps = conn.prepareStatement(sql);

			ps.setString(1, id);
			ps.setString(2, createTime);
			ps.setString(3, createUserId);
			ps.setString(4, status);
			ps.setString(5, version);
			ps.setString(6, classesId);
			ps.setString(7, dataSource);
			if (user != null) {
				ps.setString(8, user.getDepartmentId() + "");
			} else {
				ps.setString(8, null);
			}
			//ps.setObject(9, new Date().getYear()+1900);

			iter = dynamicData.entrySet().iterator();
			number = 8;
			while (iter.hasNext()) {
				number++;
				Map.Entry entry = (Map.Entry) iter.next();
				Object field = entry.getKey();
				Object value = entry.getValue();
				ps.setObject(number, value == null?null:UnicodeConverter.filterUnicode(String.valueOf(value)));
			}
			ps.executeUpdate();

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			// 关闭
			if (rs != null)
				try {
					rs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			if (ps != null)
				try {
					ps.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			if (conn != null)
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			rs = null;
			ps = null;
			conn = null;
		}
		//
		// 插入数据成功退出循环
		return id;
	}

	private String addDynamicData(String classesEn,
			Map<String, Object> dynamicData, String createTime,
			String createUserId, String status, String version,
			String classesId, String dataSource, boolean sharding,
			String shardingDataSourceId, String tableName) {

		User aUser = publicService.findUser(Integer.parseInt(createUserId));
		// 查询类
		HashMap<String, Object> queryParams = new HashMap<>();
		queryParams.put("=,nameEn", classesEn);
		List<Classes> classesList = publicService.getClasses(queryParams, 1, 1);
		Classes aClasses = null;
		if (classesList.size() > 0) {
			aClasses = classesList.get(0);
		} else {
			return null;
		}

		if (sharding) {
			// 启用分库分表代码片段 start

			// 判断shardingDataSourceId和tableName是否为空（执行单库单表插入数据）
			if (shardingDataSourceId != null
					&& !"".equals(shardingDataSourceId) && tableName != null
					&& !"".equals(tableName)) {
				ShardingDataSource aShardingDataSource = publicService
						.findShardingDataSource(Integer
								.parseInt(shardingDataSourceId));
				return shardingInsertSQL(aUser, dynamicData, createTime,
						createUserId, status, version, classesId, dataSource,
						aShardingDataSource, tableName);
			} else {
				// 获得多数据源多表情况，依次验证获得那个库那个表数据未存储至阈值
				HashMap<String, Object> srcQueryParams = new HashMap<>();
				srcQueryParams.put("=,classesEn", classesEn);
				List<ShardingRepositoryCount> srcList = publicService
						.getShardingRepositoryCount(srcQueryParams, 1, 500);
				// 知识库-数据源（查询记录阈值）
				ShardingRepositoryDataSource aShardingRepositoryDataSource = null;
				if (srcList.size() > 0) {
					HashMap<String, Object> srdQueryParams = new HashMap<>();
					srdQueryParams.put("=,classesEn", classesEn);
					srdQueryParams.put("=,shardingDataSourceId", srcList.get(0)
							.getShardingDataSourceId());
					List<ShardingRepositoryDataSource> srdList = publicService
							.getShardingRepositoryDataSource(srdQueryParams, 1,
									1);
					if (srdList.size() > 0) {
						aShardingRepositoryDataSource = srdList.get(0);
					}
				}
				for (int i = 0; i < srcList.size(); i++) {
					ShardingRepositoryCount aShardingRepositoryCount = srcList
							.get(i);
					// 获得数据源
					ShardingDataSource aShardingDataSource = publicService
							.findShardingDataSource(aShardingRepositoryCount
									.getShardingDataSourceId());
					// 表记录数小于阈值数，则满足条件新增数据
					if (aShardingRepositoryCount.getDataCount() < aShardingRepositoryDataSource
							.getShardingThreshold()) {
						return shardingInsertSQL(aUser, dynamicData,
								createTime, createUserId, status, version,
								classesId, shardingDataSourceId,
								aShardingDataSource,
								aShardingRepositoryCount.getTableName());
					}
				}
				//
			}
			// 启用分库分表代码片段 end
		} else {
			// 未启用分库分表代码片段
			if (isMongodbstorage) {

				Document document = new Document();
				if (dynamicData != null) {
					// 循环dp属性
					List<DataProperty> dpList = publicService
							.getDataProperty(aClasses);
					for (int i = 0; i < dpList.size(); i++) {
						DataProperty aDataProperty = dpList.get(i);
						Object value = dynamicData.get(aDataProperty
								.getNameEn());
						if (value != null && !"".equals(value.toString())) {
							// document.put(aDataProperty.getNameEn(),
							// decodeSpecialCharsWhenLikeUseSlash(value.toString()));
							document.put(aDataProperty.getNameEn(),UnicodeConverter.filterUnicode(value.toString()));
						}
					}
					//
				}
				String id = String.valueOf(aIdWorker.nextId());
				document.put("id", id);
				if (null != createTime && !"".equals(createTime)) {
					document.put("create_time", createTime);
				}
				document.put("create_user_id", createUserId);
				document.put("status", status);
				document.put("version", version);
				document.put("classes_id", classesId);
				document.put("data_source", dataSource);
				if (aUser != null) {
					document.put("create_org_id", aUser.getDepartmentId() + "");
				}

				MongoClientUtils.insertOne(aMongoDatabase, repositoryPrefix
						+ "." + classesEn, document);

				return id;

			} else {
				String sql = "";
				String id = String.valueOf(aIdWorker.nextId());
				//Object[] parms = new Object[9 + dynamicData.size()];
				Object[] parms = new Object[8 + dynamicData.size()];

				sql += " insert into " + repositoryPrefix + "_" + classesEn
						+ "( ";

				// 通用字段
				//sql += " id,create_time,create_user_id, status, version, classes_id, data_source,create_org_id,create_year, ";
				sql += " id,create_time,create_user_id, status, version, classes_id, data_source,create_org_id, ";

				parms[0] = id;
				parms[1] = createTime;
				parms[2] = createUserId;
				parms[3] = status;
				parms[4] = version;
				parms[5] = classesId;
				parms[6] = dataSource;

				if (aUser != null) {
					parms[7] = aUser.getDepartmentId() + "";
				} else {
					parms[7] = null;
				}
				//parms[8] = new Date().getYear()+1900;
				// 自定义字段
				Iterator iter = dynamicData.entrySet().iterator();
				int number = 7;
				while (iter.hasNext()) {
					number++;
					Map.Entry entry = (Map.Entry) iter.next();
					Object field = entry.getKey();
					Object value = entry.getValue();
					sql += field + ",";
					parms[number] = UnicodeConverter.filterUnicode(value==null?null:String.valueOf(value));
				}

				if (dynamicData.size() > 0) {
					sql = sql.substring(0, sql.length() - 1);
				}

				String sqlValues = "";
				for (int i = 0; i < parms.length; i++) {
					sqlValues += "{" + i + "},";
				}
				if (parms.length > 0) {
					sqlValues = sqlValues.substring(0, sqlValues.length() - 1);
				}

				sql += " )  values ( " + sqlValues + " ) ";

				// System.out.println("sql=" + sql);

				boolean r = super.insert(sql, parms);
				// System.out.println("执行动态表新增数据SQL返回结果集:" + r);
				if (r) {
					return id;
				} else {
					return null;
				}

			}
			//
		}
		return null;
	}

	@Override
	public boolean addDynamicData(String classesEn,
			List<Map<String, Object>> dynamicDatas, String createTime,
			String createUserId, String status, String version,
			String classesId, String dataSource, boolean sharding) {

		User aUser = publicService.findUser(Integer.parseInt(createUserId));

		// 查询类
		HashMap<String, Object> queryParams = new HashMap<>();
		queryParams.put("=,nameEn", classesEn);
		List<Classes> classesList = publicService.getClasses(queryParams, 1, 1);
		Classes aClasses = null;
		if (classesList.size() > 0) {
			aClasses = classesList.get(0);
		} else {
			return false;
		}

		if (sharding) {
			// 启用分库分表代码片段 start

			// 获得多数据源多表情况，依次验证获得那个库那个表数据未存储至阈值
			HashMap<String, Object> srcQueryParams = new HashMap<>();
			srcQueryParams.put("=,classesEn", classesEn);
			List<ShardingRepositoryCount> srcList = publicService
					.getShardingRepositoryCount(srcQueryParams, 1, 500);
			// 知识库-数据源（查询记录阈值）
			ShardingRepositoryDataSource aShardingRepositoryDataSource = null;
			if (srcList.size() > 0) {
				HashMap<String, Object> srdQueryParams = new HashMap<>();
				srdQueryParams.put("=,classesEn", classesEn);
				srdQueryParams.put("=,shardingDataSourceId", srcList.get(0)
						.getShardingDataSourceId());
				List<ShardingRepositoryDataSource> srdList = publicService
						.getShardingRepositoryDataSource(srdQueryParams, 1, 1);
				if (srdList.size() > 0) {
					aShardingRepositoryDataSource = srdList.get(0);
				}
			}
			for (int i = 0; i < srcList.size(); i++) {
				ShardingRepositoryCount aShardingRepositoryCount = srcList
						.get(i);
				// 获得数据源
				ShardingDataSource aShardingDataSource = publicService
						.findShardingDataSource(aShardingRepositoryCount
								.getShardingDataSourceId());
				// 表记录数小于阈值数，则满足条件新增数据
				if (aShardingRepositoryCount.getDataCount() < aShardingRepositoryDataSource
						.getShardingThreshold()) {

					// 存储数据
					Connection conn = null;
					PreparedStatement ps = null;
					ResultSet rs = null;

					if (dynamicDatas == null || dynamicDatas.size() == 0) {
						return false;
					}

					try {

						conn = DriverManager.getConnection(
								aShardingDataSource.getDbUrl(),
								aShardingDataSource.getDbUser(),
								aShardingDataSource.getDbPassword());

						StringBuffer sql = new StringBuffer();
						//Object[] parms = new Object[9 + dynamicDatas.get(0).size()];
						Object[] parms = new Object[8 + dynamicDatas.get(0).size()];
						sql.append(" insert into ").append(aShardingRepositoryCount.getTableName()).append("( ");
						// 通用字段
						//sql += " id,create_time,create_user_id, status, version, classes_id, data_source,create_org_id, create_year,";
						sql.append(" id,create_time,create_user_id, status, version, classes_id, data_source,create_org_id,");
						// 自定义字段
						Iterator iter = dynamicDatas.get(0).entrySet()
								.iterator();
						int number = 8;
						while (iter.hasNext()) {
							number++;
							Map.Entry entry = (Map.Entry) iter.next();
							Object field = entry.getKey();
							Object value = entry.getValue();
							sql.append(field).append(",");
						}

						if (dynamicDatas.get(0).size() > 0) {
							//sql = sql.substring(0, sql.length() - 1);
							sql = sql.delete(sql.length() - 1, sql.length());
						}

						StringBuffer sqlValues = new StringBuffer();
						for (int k = 0; k < parms.length; k++) {
							sqlValues.append("?,");
						}
						if (parms.length > 0) {
							///sqlValues = sqlValues.substring(0,sqlValues.length() - 1);
							sqlValues = sqlValues.delete(sqlValues.length() - 1, sqlValues.length());
						}

						sql.append(" )  values ( ").append(sqlValues.toString()).append(" ) ");
						System.out.println("sql=" + sql);

						ps = conn.prepareStatement(sql.toString());
						conn.setAutoCommit(false);
						// 循环
						for (int k = 0; k < dynamicDatas.size(); k++) {
							Map<String, Object> dynamicData = dynamicDatas
									.get(k);

							// 通用字段
							String id = String.valueOf(aIdWorker.nextId());
							ps.setString(1, id);
							ps.setString(2, createTime);
							ps.setString(3, createUserId);
							ps.setString(4, status);
							ps.setString(5, version);
							ps.setString(6, classesId);
							ps.setString(7, dataSource);
							if (aUser != null) {
								ps.setString(8, aUser.getDepartmentId() + "");
							} else {
								ps.setString(8, null);
							}
							//ps.setObject(9, new Date().getYear()+1900);

							// 自定义字段
							Iterator dyIter = dynamicData.entrySet().iterator();
							int dyNumber = 8;
							while (dyIter.hasNext()) {
								dyNumber++;
								Map.Entry entry = (Map.Entry) dyIter.next();
								Object field = entry.getKey();
								Object value = entry.getValue();
								ps.setObject(dyNumber, value == null?null:UnicodeConverter.filterUnicode(String.valueOf(value)));
							}

							// 优化插入第二步---插入代码打包，等一定量后再一起插入。
							ps.addBatch();
							// 每1000次提交一次---可以设置不同的大小；如50，100，200，500，1000等等
							if ((k != 0 && k % 1000 == 0)
									|| k == dynamicDatas.size() - 1) {
								ps.executeBatch();
								// 优化插入第三步---提交，批量插入数据库中。
								conn.commit();
								ps.clearBatch(); // 提交后，Batch清空。
							}

						}

					} catch (Exception e) {
						e.printStackTrace();
						return false;
					} finally {
						// 关闭
						if (rs != null)
							try {
								rs.close();
							} catch (SQLException e) {
								e.printStackTrace();
							}
						if (ps != null)
							try {
								ps.close();
							} catch (SQLException e) {
								e.printStackTrace();
							}
						if (conn != null)
							try {
								conn.close();
							} catch (SQLException e) {
								e.printStackTrace();
							}
						rs = null;
						ps = null;
						conn = null;
					}
					// 执行完毕
					return true;
					//
				}
			}
			// 启用分库分表代码片段 end
		} else {
			// 未启用分库分表
			if (isMongodbstorage) {
				List<Document> documents = new ArrayList<Document>();
				Document document = null;

				for (int k = 0; k < dynamicDatas.size(); k++) {
					document = new Document();
					Map<String, Object> dynamicData = dynamicDatas.get(k);
					if (dynamicData != null) {
						// 循环dp属性
						List<DataProperty> dpList = publicService
								.getDataProperty(aClasses);
						for (int i = 0; i < dpList.size(); i++) {
							DataProperty aDataProperty = dpList.get(i);
							Object value = dynamicData.get(aDataProperty
									.getNameEn());
							if (value != null && !"".equals(value.toString())) {
								// document.put(aDataProperty.getNameEn(),decodeSpecialCharsWhenLikeUseSlash(value.toString()));
								document.put(aDataProperty.getNameEn(),
										UnicodeConverter.filterUnicode(value.toString()));
							}
						}
						//
					}
					String id = String.valueOf(aIdWorker.nextId());
					document.put("id", id); // 主键ID
					if (null != createTime && !"".equals(createTime)) {
						document.put("create_time", createTime);
					}
					document.put("create_user_id", createUserId);
					document.put("status", status);
					document.put("version", version);
					document.put("classes_id", classesId);
					document.put("data_source", dataSource);
					//document.put("create_year", new Date().getYear()+1900);
					if (aUser != null) {
						document.put("create_org_id", aUser.getDepartmentId()
								+ "");
					}
					documents.add(document);
				}
				if (documents.size() > 0) {
					MongoClientUtils.insertMany(aMongoDatabase,
							repositoryPrefix + "." + classesEn, documents);
					return true;
				}

				return false;

			} else {
				Connection conn = null;
				PreparedStatement ps = null;
				ResultSet rs = null;

				if (dynamicDatas == null || dynamicDatas.size() == 0) {
					return false;
				}

				try {
					conn = DriverManager.getConnection(
							XxlConfClient.get("dal.jdbc.url", ""),
							XxlConfClient.get("dal.jdbc.username", "root"),
							XxlConfClient.get("dal.jdbc.password", ""));
					String sql = "";
					//Object[] parms = new Object[9 + dynamicDatas.get(0).size()];
					Object[] parms = new Object[8 + dynamicDatas.get(0).size()];
					sql += " insert into " + repositoryPrefix + "_" + classesEn
							+ "( ";
					// 通用字段
					//sql += " id,create_time,create_user_id, status, version, classes_id, data_source,create_org_id,create_year, ";
					sql += " id,create_time,create_user_id, status, version, classes_id, data_source,create_org_id, ";
					// 自定义字段
					Iterator iter = dynamicDatas.get(0).entrySet().iterator();
					int number = 7;
					while (iter.hasNext()) {
						number++;
						Map.Entry entry = (Map.Entry) iter.next();
						Object field = entry.getKey();
						Object value = entry.getValue();
						sql += field + ",";
					}

					if (dynamicDatas.get(0).size() > 0) {
						sql = sql.substring(0, sql.length() - 1);
					}

					String sqlValues = "";
					for (int i = 0; i < parms.length; i++) {
						sqlValues += "?,";
					}
					if (parms.length > 0) {
						sqlValues = sqlValues.substring(0,
								sqlValues.length() - 1);
					}

					sql += " )  values ( " + sqlValues + " ) ";
					System.out.println("sql=" + sql);

					ps = conn.prepareStatement(sql);
					conn.setAutoCommit(false);
					// 循环
					for (int k = 0; k < dynamicDatas.size(); k++) {
						Map<String, Object> dynamicData = dynamicDatas.get(k);

						// 通用字段
						String id = String.valueOf(aIdWorker.nextId());
						ps.setString(1, id);
						ps.setString(2, createTime);
						ps.setString(3, createUserId);
						ps.setString(4, status);
						ps.setString(5, version);
						ps.setString(6, classesId);
						ps.setString(7, dataSource);
						if (aUser != null) {
							ps.setString(8, aUser.getDepartmentId() + "");
						} else {
							ps.setString(8, null);
						}
						//ps.setObject(9, new Date().getYear()+1900);
						
						// 自定义字段
						Iterator dyIter = dynamicData.entrySet().iterator();
						int dyNumber = 8;
						while (dyIter.hasNext()) {
							dyNumber++;
							Map.Entry entry = (Map.Entry) dyIter.next();
							Object field = entry.getKey();
							Object value = entry.getValue();
							ps.setObject(dyNumber, value == null?null:UnicodeConverter.filterUnicode(String.valueOf(value)));
						}

						// 优化插入第二步---插入代码打包，等一定量后再一起插入。
						ps.addBatch();
						// 每1000次提交一次---可以设置不同的大小；如50，100，200，500，1000等等
						if ((k != 0 && k % 1000 == 0)
								|| k == dynamicDatas.size() - 1) {
							ps.executeBatch();
							// 优化插入第三步---提交，批量插入数据库中。
							conn.commit();
							ps.clearBatch(); // 提交后，Batch清空。
						}

					}

				} catch (Exception e) {
					e.printStackTrace();
					return false;
				} finally {
					// 关闭
					if (rs != null)
						try {
							rs.close();
						} catch (SQLException e) {
							e.printStackTrace();
						}
					if (ps != null)
						try {
							ps.close();
						} catch (SQLException e) {
							e.printStackTrace();
						}
					if (conn != null)
						try {
							conn.close();
						} catch (SQLException e) {
							e.printStackTrace();
						}
					rs = null;
					ps = null;
					conn = null;
				}
				// 执行完毕
				return true;
			}
			//
		}
		return false;
	}

	@Override
	public void deleteShardingRepositoryTable(String classesEn,
			String repositoryDataSourceId) {
		// 查询知识库-数据源关联表
		ShardingRepositoryDataSource aShardingRepositoryDataSource = publicService
				.findShardingRepositoryDataSource(Integer
						.parseInt(repositoryDataSourceId));
		// 数据源
		ShardingDataSource aShardingDataSource = publicService
				.findShardingDataSource(aShardingRepositoryDataSource
						.getShardingDataSourceId());
		HashMap<String, Object> queryParams = new HashMap<>();
		queryParams.put("=,classesEn", classesEn);
		queryParams.put("=,shardingDataSourceId",
				aShardingRepositoryDataSource.getShardingDataSourceId());
		List<ShardingRepositoryCount> srcList = publicService
				.getShardingRepositoryCount(queryParams, 1, 500);
		for (int i = 0; i < srcList.size(); i++) {
			ShardingRepositoryCount aShardingRepositoryCount = srcList.get(i);
			// 删除自动创建表
			String sql = DBUtils.deleteTable(dbStyle,
					aShardingRepositoryCount.getTableName());
			// 执行sql语句
			Connection conn = null;
			PreparedStatement ps = null;
			ResultSet rs = null;

			try {
				conn = DriverManager.getConnection(
						aShardingDataSource.getDbUrl(),
						aShardingDataSource.getDbUser(),
						aShardingDataSource.getDbPassword());

				ps = conn.prepareStatement(sql);
				ps.execute(sql);

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				// 关闭
				if (rs != null)
					try {
						rs.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				if (ps != null)
					try {
						ps.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				if (conn != null)
					try {
						conn.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				rs = null;
				ps = null;
				conn = null;
			}
			// 删除分库分表-记录数表
			baseService.deleteShardingRepositoryCount(aShardingRepositoryCount);
		}
	}

	@Override
	public String addDynamicData(String classesEn,
			Map<String, Object> dynamicData, String createTime,
			String createUserId, String status, String version,
			String classesId, String dataSource, String shardingDataSourceId,
			String tableName) {
		return addDynamicData(classesEn, dynamicData, createTime, createUserId,
				status, version, classesId, dataSource, true,
				shardingDataSourceId, tableName);
	}

	@Override
	public void editDynamicData(String classesEn,
			Map<String, Object> dynamicData, String updateTime,
			String updateUserId, String status, String version, String id,
			String shardingDataSourceId, String tableName) {

		User aUser = publicService.findUser(Integer.parseInt(updateUserId));

		// 分库分表-固定库和表
		if (shardingDataSourceId != null && !"".equals(shardingDataSourceId)
				&& tableName != null && !"".equals(tableName)) {
			ShardingDataSource aShardingDataSource = publicService
					.findShardingDataSource(Integer
							.parseInt(shardingDataSourceId));

			// 执行sql语句
			Connection conn = null;
			PreparedStatement ps = null;
			ResultSet rs = null;

			try {
				conn = DriverManager.getConnection(
						aShardingDataSource.getDbUrl(),
						aShardingDataSource.getDbUser(),
						aShardingDataSource.getDbPassword());

				String sql = "";

				sql += " update " + tableName + " set ";

				// 通用字段
				sql += " update_time=?,update_user_id=?,status=?, version=?, update_org_id=?, ";

				// 自定义字段
				Iterator iter = dynamicData.entrySet().iterator();
				while (iter.hasNext()) {
					Map.Entry entry = (Map.Entry) iter.next();
					Object field = entry.getKey();
					Object value = entry.getValue();
					sql += field + "=?,";
				}

				if (dynamicData.size() > 0) {
					sql = sql.substring(0, sql.length() - 1);
				}

				sql += " where id=? ";

				System.out.println("sql=" + sql);

				ps = conn.prepareStatement(sql);

				ps.setString(1, updateTime);
				ps.setString(2, updateUserId);
				ps.setString(3, status);
				ps.setString(4, version);

				if (aUser != null) {
					ps.setString(5, aUser.getDepartmentId() + "");
				} else {
					ps.setString(5, null);
				}

				// 自定义字段
				iter = dynamicData.entrySet().iterator();
				int number = 5;
				while (iter.hasNext()) {
					number++;
					Map.Entry entry = (Map.Entry) iter.next();
					Object field = entry.getKey();
					Object value = entry.getValue();
					ps.setObject(number, value == null?null:UnicodeConverter.filterUnicode(String.valueOf(value)));
				}

				ps.setString((number + 1), id);

				ps.executeUpdate();

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				// 关闭
				if (rs != null)
					try {
						rs.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				if (ps != null)
					try {
						ps.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				if (conn != null)
					try {
						conn.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				rs = null;
				ps = null;
				conn = null;
			}
			//

		} else {

			if (isMongodbstorage) {

				dynamicData.put("status", status);
				dynamicData.put("version", version);
				dynamicData.put("update_user_id", updateUserId);
				if (updateTime != null && !"".equals(updateTime)) {
					dynamicData.put("update_time", updateTime);
				}
				if (aUser != null) {
					dynamicData.put("update_org_id", aUser.getDepartmentId()
							+ "");
				}

				MongoClientUtils.edit(aMongoDatabase, repositoryPrefix + "."
						+ classesEn, id, dynamicData);

			} else {
				String sql = "";
				Object[] parms = new Object[6 + dynamicData.size()];

				sql += " update " + repositoryPrefix + "_" + classesEn
						+ " set ";

				// 通用字段
				sql += " update_time={0},update_user_id={1},status={2}, version={3}, update_org_id={4}, ";
				parms[0] = updateTime;
				parms[1] = updateUserId;
				parms[2] = status;
				parms[3] = version;

				if (aUser != null) {
					parms[4] = aUser.getDepartmentId() + "";
				} else {
					parms[4] = null;
				}

				// 自定义字段
				Iterator iter = dynamicData.entrySet().iterator();
				int number = 4;
				while (iter.hasNext()) {
					number++;
					Map.Entry entry = (Map.Entry) iter.next();
					Object field = entry.getKey();
					Object value = entry.getValue();
					sql += field + "={" + number + "},";
					parms[number] = value == null?null:UnicodeConverter.filterUnicode(String.valueOf(value));
				}

				if (dynamicData.size() > 0) {
					sql = sql.substring(0, sql.length() - 1);
				}

				sql += " where id={" + (parms.length - 1) + "} ";
				parms[parms.length - 1] = id;

				System.out.println("sql=" + sql);
				boolean b = super.update(sql, parms);
				System.out.println("执行编辑动态表SQL返回结果集:" + b);
			}
			//
		}
		//
	}

	@Override
	public boolean editDynamicData(String classesEn,
			Map<String, Object> dynamicData, Map<String, Object> conditions,
			String updateTime, String updateUserId, String status,
			String version, String shardingDataSourceId, String tableName) {

		User aUser = publicService.findUser(Integer.parseInt(updateUserId));

		if (shardingDataSourceId != null && !"".equals(shardingDataSourceId)
				&& tableName != null && !"".equals(tableName)) {
			ShardingDataSource aShardingDataSource = publicService
					.findShardingDataSource(Integer
							.parseInt(shardingDataSourceId));

			// 执行sql语句
			Connection conn = null;
			PreparedStatement ps = null;
			ResultSet rs = null;

			try {
				conn = DriverManager.getConnection(
						aShardingDataSource.getDbUrl(),
						aShardingDataSource.getDbUser(),
						aShardingDataSource.getDbPassword());

				int dynamicDataSize = 0;
				int conditionsSize = 0;
				if (dynamicData != null) {
					dynamicDataSize = dynamicData.size();
				}
				if (conditions != null) {
					conditionsSize = conditions.size();
				}
				String sql = "";
				Object[] parms = new Object[5 + dynamicDataSize
						+ conditionsSize];

				sql += " update " + tableName + " set ";

				// 通用字段
				sql += " update_time=?,update_user_id=?,status=?, version=?, update_org_id=?, ";
				parms[0] = updateTime;
				parms[1] = updateUserId;
				parms[2] = status;
				parms[3] = version;

				if (aUser != null) {
					parms[4] = aUser.getDepartmentId() + "";
				} else {
					parms[4] = null;
				}

				// 自定义字段
				if (dynamicData != null && dynamicData.size() > 0) {
					Iterator iter = dynamicData.entrySet().iterator();
					int number = 4;
					while (iter.hasNext()) {
						number++;
						Map.Entry entry = (Map.Entry) iter.next();
						Object field = entry.getKey();
						Object value = entry.getValue();
						sql += field + "=?,";
						parms[number] = value==null?null:UnicodeConverter.filterUnicode(String.valueOf(value));
					}
					if (dynamicData.size() > 0) {
						sql = sql.substring(0, sql.length() - 1);
					}
				}

				if (conditions != null && conditions.size() > 0) {
					sql += " where ";
					Iterator iter = conditions.entrySet().iterator();
					int number = 4 + dynamicDataSize;
					while (iter.hasNext()) {
						number++;
						Map.Entry entry = (Map.Entry) iter.next();
						Object field = entry.getKey();
						Object value = entry.getValue();
						sql += field + "=? AND ";
						parms[number] = value;
					}
					if (conditions.size() > 0) {
						sql = sql.substring(0, sql.length() - 4);
					}

				}

				System.out.println("sql=" + sql);
				ps = conn.prepareStatement(sql);

				for (int i = 0; i < parms.length; i++) {
					ps.setObject((i + 1), parms[i]);
				}
				ps.executeUpdate();

			} catch (Exception e) {
				e.printStackTrace();
				return false;
			} finally {
				// 关闭
				if (rs != null)
					try {
						rs.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				if (ps != null)
					try {
						ps.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				if (conn != null)
					try {
						conn.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				rs = null;
				ps = null;
				conn = null;
			}

		} else {
			if (isMongodbstorage) {
				dynamicData.put("status", status);
				dynamicData.put("version", version);
				dynamicData.put("update_user_id", updateUserId);
				if (updateTime != null && !"".equals(updateTime)) {
					dynamicData.put("update_time", updateTime);
				}
				if (aUser != null) {
					dynamicData.put("update_org_id", aUser.getDepartmentId()
							+ "");
				}
				MongoClientUtils.edit(aMongoDatabase, repositoryPrefix + "."
						+ classesEn, conditions, dynamicData);
				return false;
			} else {
				int dynamicDataSize = 0;
				int conditionsSize = 0;
				if (dynamicData != null) {
					dynamicDataSize = dynamicData.size();
				}
				if (conditions != null) {
					conditionsSize = conditions.size();
				}
				String sql = "";
				Object[] parms = new Object[5 + dynamicDataSize
						+ conditionsSize];

				sql += " update " + repositoryPrefix + "_" + classesEn
						+ " set ";

				// 通用字段
				sql += " update_time={0},update_user_id={1},status={2}, version={3}, update_org_id={4}, ";
				parms[0] = updateTime;
				parms[1] = updateUserId;
				parms[2] = status;
				parms[3] = version;

				if (aUser != null) {
					parms[4] = aUser.getDepartmentId() + "";
				} else {
					parms[4] = null;
				}

				// 自定义字段
				if (dynamicData != null && dynamicData.size() > 0) {
					Iterator iter = dynamicData.entrySet().iterator();
					int number = 4;
					while (iter.hasNext()) {
						number++;
						Map.Entry entry = (Map.Entry) iter.next();
						Object field = entry.getKey();
						Object value = entry.getValue();
						sql += field + "={" + number + "},";
						parms[number] = value==null?null:UnicodeConverter.filterUnicode(String.valueOf(value));
					}

					if (dynamicData.size() > 0) {
						sql = sql.substring(0, sql.length() - 1);
					}
				}

				if (conditions != null && conditions.size() > 0) {
					sql += " where ";

					Iterator iter = conditions.entrySet().iterator();
					int number = 4 + dynamicDataSize;
					while (iter.hasNext()) {
						number++;
						Map.Entry entry = (Map.Entry) iter.next();
						Object field = entry.getKey();
						Object value = entry.getValue();
						sql += field + "={" + number + "} AND ";
						parms[number] = value;
					}

					if (conditions.size() > 0) {
						sql = sql.substring(0, sql.length() - 4);
					}

				}

				System.out.println("sql=" + sql);
				boolean b = super.update(sql + "", parms);
				System.out.println("执行编辑动态表SQL返回结果集:" + b);
				return b;
			}

		}
		return false;
	}

	@Override
	public void editDynamicData(String classesEn,
			List<Map<String, Object>> dynamicDatas, String updateTime,
			String updateUserId, String status, String version,
			String shardingDataSourceId, String tableName) {

		User aUser = publicService.findUser(Integer.parseInt(updateUserId));

		if (shardingDataSourceId != null && !"".equals(shardingDataSourceId)
				&& tableName != null && !"".equals(tableName)) {
			ShardingDataSource aShardingDataSource = publicService
					.findShardingDataSource(Integer
							.parseInt(shardingDataSourceId));

			Connection conn = null;
			PreparedStatement ps = null;
			ResultSet rs = null;

			if (dynamicDatas == null || dynamicDatas.size() == 0) {
				return;
			}
			try {
				conn = DriverManager.getConnection(
						aShardingDataSource.getDbUrl(),
						aShardingDataSource.getDbUser(),
						aShardingDataSource.getDbPassword());

				String sql = " update "
						+ tableName
						+ " set update_time=?,update_user_id=?,status=?,version=? where id=?";

				ps = conn.prepareStatement(sql);
				conn.setAutoCommit(false);
				// 循环
				for (int k = 0; k < dynamicDatas.size(); k++) {
					Map<String, Object> dynamicData = dynamicDatas.get(k);
					Object object = dynamicData.get("id");
					ps.setObject(1, updateTime);
					ps.setObject(2, updateUserId);
					ps.setObject(3, status);
					ps.setObject(4, version);
					ps.setObject(5, object);
					// 优化插入第二步---插入代码打包，等一定量后再一起插入。
					ps.addBatch();
					// 每1000次提交一次---可以设置不同的大小；如50，100，200，500，1000等等
					if ((k != 0 && k % 1000 == 0)
							|| k == dynamicDatas.size() - 1) {
						ps.executeBatch();
						// 优化插入第三步---提交，批量插入数据库中。
						conn.commit();
						ps.clearBatch(); // 提交后，Batch清空。
					}
					//
				}
			} catch (Exception e) {
				e.printStackTrace();
				return;
			} finally {
				// 关闭
				if (rs != null)
					try {
						rs.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				if (ps != null)
					try {
						ps.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				if (conn != null)
					try {
						conn.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				rs = null;
				ps = null;
				conn = null;
			}
			//
		} else {
			if (isMongodbstorage) {
				String[] ids = new String[dynamicDatas.size()];
				for (int i = 0; i < dynamicDatas.size(); i++) {
					ids[i] = dynamicDatas.get(i).get("id").toString();
				}
				Map<String, Object> dynamicData = new HashMap<String, Object>();
				dynamicData.put("status", status);
				dynamicData.put("version", version);
				dynamicData.put("update_user_id", updateUserId);
				if (updateTime != null && !"".equals(updateTime)) {
					dynamicData.put("update_time", updateTime);
				}
				if (aUser != null) {
					dynamicData.put("update_org_id", aUser.getDepartmentId()
							+ "");
				}
				MongoClientUtils.editByIds(aMongoDatabase, repositoryPrefix
						+ "." + classesEn, ids, dynamicData);
			} else {
				Connection conn = null;
				PreparedStatement ps = null;
				ResultSet rs = null;

				if (dynamicDatas == null || dynamicDatas.size() == 0) {
					return;
				}
				try {
					conn = DriverManager.getConnection(
							XxlConfClient.get("dal.jdbc.url", ""),
							XxlConfClient.get("dal.jdbc.username", "root"),
							XxlConfClient.get("dal.jdbc.password", ""));
					String sql = "";
					Object[] parms = new Object[8 + dynamicDatas.get(0).size()];
					sql += " update "
							+ repositoryPrefix
							+ "_"
							+ classesEn
							+ " set update_time=?,update_user_id=?,status=?,version=? where id=?";

					ps = conn.prepareStatement(sql);
					conn.setAutoCommit(false);
					// 循环
					for (int k = 0; k < dynamicDatas.size(); k++) {
						Map<String, Object> dynamicData = dynamicDatas.get(k);
						Object object = dynamicData.get("id");
						ps.setObject(1, updateTime);
						ps.setObject(2, updateUserId);
						ps.setObject(3, status);
						ps.setObject(4, version);
						ps.setObject(5, object);
						// 优化插入第二步---插入代码打包，等一定量后再一起插入。
						ps.addBatch();
						// 每1000次提交一次---可以设置不同的大小；如50，100，200，500，1000等等
						if ((k != 0 && k % 1000 == 0)
								|| k == dynamicDatas.size() - 1) {
							ps.executeBatch();
							// 优化插入第三步---提交，批量插入数据库中。
							conn.commit();
							ps.clearBatch(); // 提交后，Batch清空。
						}

					}
				} catch (Exception e) {
					e.printStackTrace();
					return;
				} finally {
					// 关闭
					if (rs != null)
						try {
							rs.close();
						} catch (SQLException e) {
							e.printStackTrace();
						}
					if (ps != null)
						try {
							ps.close();
						} catch (SQLException e) {
							e.printStackTrace();
						}
					if (conn != null)
						try {
							conn.close();
						} catch (SQLException e) {
							e.printStackTrace();
						}
					rs = null;
					ps = null;
					conn = null;
				}
			}
			//
		}
	}

	@Override
	public void editDynamicDataCreateUser(String classesEn, String id,
			String userId, String shardingDataSourceId, String tableName) {

		User aUser = publicService.findUser(Integer.parseInt(userId));

		if (shardingDataSourceId != null && !"".equals(shardingDataSourceId)
				&& tableName != null && !"".equals(tableName)) {
			ShardingDataSource aShardingDataSource = publicService
					.findShardingDataSource(Integer
							.parseInt(shardingDataSourceId));

			// 执行sql语句
			Connection conn = null;
			PreparedStatement ps = null;
			ResultSet rs = null;

			try {
				conn = DriverManager.getConnection(
						aShardingDataSource.getDbUrl(),
						aShardingDataSource.getDbUser(),
						aShardingDataSource.getDbPassword());

				String sql = " update " + tableName
						+ " set create_user_id=?,create_org_id=? where id=? ";
				System.out.println("sql=" + sql);

				ps = conn.prepareStatement(sql);
				ps.setInt(1, aUser.getId());
				ps.setInt(2, aUser.getDepartmentId());
				ps.setString(3, id);

				ps.executeUpdate();

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				// 关闭
				if (rs != null)
					try {
						rs.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				if (ps != null)
					try {
						ps.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				if (conn != null)
					try {
						conn.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				rs = null;
				ps = null;
				conn = null;
			}
			//

		} else {
			if (isMongodbstorage) {
				Map<String, Object> dynamicData = new HashMap<String, Object>();
				dynamicData.put("create_user_id", aUser.getId() + "");
				if (aUser != null) {
					dynamicData.put("create_org_id", aUser.getDepartmentId()
							+ "");
				}
				MongoClientUtils.edit(aMongoDatabase, repositoryPrefix + "."
						+ classesEn, id, dynamicData);
			} else {
				String sql = "";
				sql += " update "
						+ repositoryPrefix
						+ "_"
						+ classesEn
						+ " set create_user_id={0},create_org_id={1} where id={2} ";
				System.out.println("sql=" + sql);
				Object[] parms = new Object[] { aUser.getId(),
						aUser.getDepartmentId(), id };
				boolean b = super.update(sql, parms);
				System.out.println("执行动态表编辑创建人SQL返回结果集:" + b);
			}
		}
		//
	}

	@Override
	public void deleteDynamicData(String classesEn,
			Map<String, Object> dynamicData, String shardingDataSourceId,
			String tableName) {
		if (shardingDataSourceId != null && !"".equals(shardingDataSourceId)
				&& tableName != null && !"".equals(tableName)) {
			ShardingDataSource aShardingDataSource = publicService
					.findShardingDataSource(Integer
							.parseInt(shardingDataSourceId));

			// 执行sql语句
			Connection conn = null;
			PreparedStatement ps = null;

			try {
				conn = DriverManager.getConnection(
						aShardingDataSource.getDbUrl(),
						aShardingDataSource.getDbUser(),
						aShardingDataSource.getDbPassword());

				String sql = " delete from " + tableName + " where id=? ";

				ps = conn.prepareStatement(sql);
				ps.setString(1, dynamicData.get("id").toString());
				ps.executeUpdate();

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				// 关闭
				if (ps != null)
					try {
						ps.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				if (conn != null)
					try {
						conn.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				ps = null;
				conn = null;
			}

		} else {
			if (isMongodbstorage) {
				MongoClientUtils.delete(aMongoDatabase, repositoryPrefix + "."
						+ classesEn, dynamicData.get("id").toString());
			} else {
				String sql = " delete from " + repositoryPrefix + "_"
						+ classesEn + " where id={0} ";
				System.out.println("sql=" + sql);
				boolean b = super.delete(sql,
						new Object[] { dynamicData.get("id") });
				System.out.println("执行删除SQL返回结果集:" + b);
			}
			//
		}
	}

	@Override
	public Map<String, Object> findDynamicData(String classesEn, String id,
			String shardingDataSourceId, String tableName) {
		if (shardingDataSourceId != null && !"".equals(shardingDataSourceId)
				&& tableName != null && !"".equals(tableName)) {
			ShardingDataSource aShardingDataSource = publicService
					.findShardingDataSource(Integer
							.parseInt(shardingDataSourceId));
			String sql = " select * from " + tableName + " where id=? ";

			// 执行sql语句
			Connection conn = null;
			PreparedStatement ps = null;
			ResultSet rs = null;
			Map<String, Object> r = null;

			try {
				conn = DriverManager.getConnection(
						aShardingDataSource.getDbUrl(),
						aShardingDataSource.getDbUser(),
						aShardingDataSource.getDbPassword());

				ps = conn.prepareStatement(sql);
				ps.setString(1, id);

				rs = ps.executeQuery();
				ResultSetMetaData data = rs.getMetaData();
				while (rs.next()) {
					r = new HashMap<String, Object>();
					for (int i = 1; i <= data.getColumnCount(); i++) {
						String columnName = data.getColumnLabel(i);
						if(rs.getObject(i)!=null){
							r.put(columnName, UnicodeConverter.unicode2String(String.valueOf(rs.getObject(i))));
						}
					}
				}

			} catch (Exception e) {
				e.printStackTrace();
				return null;
			} finally {
				// 关闭
				if (rs != null)
					try {
						rs.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				if (ps != null)
					try {
						ps.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				if (conn != null)
					try {
						conn.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				rs = null;
				ps = null;
				conn = null;
			}
			return r;
		} else {
			if (isMongodbstorage) {
				Document aDocument = MongoClientUtils.find(aMongoDatabase,
						repositoryPrefix + "." + classesEn, id);
				Map<String, Object> r = new HashMap<String, Object>();
				Iterator iter = aDocument.entrySet().iterator();
				while (iter.hasNext()) {
					Map.Entry entry = (Map.Entry) iter.next();
					Object field = entry.getKey();
					Object value = entry.getValue();
					if(value != null){
						r.put(field.toString(), UnicodeConverter.unicode2String(String.valueOf(value)));
					}
				}
				r.remove("_id");
				return r;
			} else {
				String sql = " select * from " + repositoryPrefix + "_"
						+ classesEn + " where id={0}";
				Map<String, Object> r = super.selectOne(sql,new Object[] { id });
				if(null != r && !"".equals(r)){
					for (String key : r.keySet()) {
						if(r.get(key) != null){
							r.put(key, UnicodeConverter.unicode2String(String.valueOf(r.get(key))));
						}
					}
				}
				return r;
			}
		}
		//
	}

	@Override
	public Map<String, Object> findDynamicData(String classesEn, String id,
			String fields, String shardingDataSourceId, String tableName) {

		if (fields == null || "".equals(fields)) {
			return null;
		}

		if (shardingDataSourceId != null && !"".equals(shardingDataSourceId)
				&& tableName != null && !"".equals(tableName)) {
			ShardingDataSource aShardingDataSource = publicService
					.findShardingDataSource(Integer
							.parseInt(shardingDataSourceId));

			// 执行sql语句
			Connection conn = null;
			PreparedStatement ps = null;
			ResultSet rs = null;
			Map<String, Object> r = null;

			try {
				conn = DriverManager.getConnection(
						aShardingDataSource.getDbUrl(),
						aShardingDataSource.getDbUser(),
						aShardingDataSource.getDbPassword());

				
				String fieldsStr="id,status,";
				String[] split = fields.split(",");
				for (int i = 0; i < split.length; i++) {
					DataProperty dp = publicService.findDataProperty(Integer.parseInt(split[i]));
					fieldsStr += dp.getNameEn();
					if(i != split.length-1){
						fieldsStr += ",";
					}
				}
				String sql = " select " + fieldsStr + " from " + tableName
						+ " where id=? ";

				ps = conn.prepareStatement(sql);
				ps.setString(1, id);

				rs = ps.executeQuery();
				ResultSetMetaData data = rs.getMetaData();
				while (rs.next()) {
					r = new HashMap<String, Object>();
					for (int i = 1; i <= data.getColumnCount(); i++) {
						String columnName = data.getColumnLabel(i);
						if(rs.getObject(i) != null){
							r.put(columnName, UnicodeConverter.unicode2String(String.valueOf(rs.getObject(i))));
						}
					}
				}

			} catch (Exception e) {
				e.printStackTrace();
				return null;
			} finally {
				// 关闭
				if (rs != null)
					try {
						rs.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				if (ps != null)
					try {
						ps.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				if (conn != null)
					try {
						conn.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				rs = null;
				ps = null;
				conn = null;
			}
			return r;

		} else {
			if (isMongodbstorage) {
				Document aDocument = MongoClientUtils.find(aMongoDatabase,
						repositoryPrefix + "." + classesEn, id);
				Map<String, Object> r = new HashMap<String, Object>();
				String[] fieldArray = fields.split(",");
				for (int i = 0; i < fieldArray.length; i++) {
					DataProperty aDataProperty = publicService
							.findDataProperty(Integer.parseInt(fieldArray[i]));
					if(aDocument.get(aDataProperty.getNameEn()) != null){
						r.put(aDataProperty.getNameEn(),
								UnicodeConverter.unicode2String(String.valueOf(aDocument.get(aDataProperty.getNameEn()))));
					}
				}
				return r;
			} else {
				// String[] fieldArray = fields.split(",");
				// String selectSQL = "id,";
				// for (int i = 0; i < fieldArray.length; i++) {
				// DataProperty aDataProperty = publicService
				// .findDataProperty(Integer.parseInt(fieldArray[i]));
				// selectSQL += aDataProperty.getNameEn() + ",";
				// }
				// selectSQL = selectSQL.substring(0, selectSQL.length() - 1);
				String fieldsStr="id,status,";
				String[] split = fields.split(",");
				for (int i = 0; i < split.length; i++) {
					DataProperty dp = publicService.findDataProperty(Integer.parseInt(split[i]));
					fieldsStr += dp.getNameEn();
					if(i != split.length-1){
						fieldsStr += ",";
					}
				}
				String sql = " select " + fieldsStr + " from " + repositoryPrefix
						+ "_" + classesEn + " where id={0}";
				Map<String, Object> r = super.selectOne(sql,
						new Object[] { id });
				if(r!=null){
					for (String key : r.keySet()) {
						if(r.get(key) != null){
							r.put(key, UnicodeConverter.unicode2String(String.valueOf(r.get(key))));
						}
					}
				}
				return r;
			}
			//
		}
	}

	@Override
	public List<Map<String, Object>> getDynamicData(String classesEn,
			Map<String, Object> conditions, int pageNumber, int pageSize,
			String shardingDataSourceId, String tableName) {
		return getDynamicData(classesEn, conditions, null, null, pageNumber,
				pageSize, shardingDataSourceId, tableName);
	}

	@Override
	public List<Map<String, Object>> getDynamicDataList(String classesEn,
			String showField, Map<String, Object> conditions, int pageNumber,
			int pageSize, String shardingDataSourceId, String tableName) {
		return getDynamicDataList(classesEn, showField, conditions, null, null,
				pageNumber, pageSize, shardingDataSourceId, tableName);
	}

	@Override
	public List<Map<String, Object>> getDynamicDataList(String classesEn,
			String showField, Map<String, Object> conditions,
			String orderByField, String orderByValue, int pageNumber,
			int pageSize, String shardingDataSourceId, String tableName) {

		if (orderByField == null || orderByValue == null) {
			orderByField = "create_time";
			orderByValue = "desc";
		}

		if (shardingDataSourceId != null && !"".equals(shardingDataSourceId)
				&& tableName != null && !"".equals(tableName)) {
			ShardingDataSource aShardingDataSource = publicService
					.findShardingDataSource(Integer
							.parseInt(shardingDataSourceId));

			String sql = "";
			if (conditions == null) {
				sql = " select " + showField + " from " + tableName;
				sql += " order by " + orderByField + " " + orderByValue
						+ " limit ?,? ";
			} else {
				sql = " select " + showField + " from " + tableName
						+ " where 1=1 ";
				Iterator iter = conditions.entrySet().iterator();
				while (iter.hasNext()) {
					Map.Entry entry = (Map.Entry) iter.next();
					Object field = entry.getKey();
					Object value = entry.getValue();
					if (field.toString().startsWith("=")) {
						sql += " and "
								+ field.toString().substring(1)
								+ " = '"
								+ decodeSpecialCharsWhenLikeUseSlash(value
										.toString()) + "' ";
					} else if (field.toString().startsWith("><")) {
						sql += " and " + field.toString().substring(2)
								+ " >= '" + value.toString().split("#")[0]
								+ "' " + " and "
								+ field.toString().substring(2) + " <= '"
								+ value.toString().split("#")[1] + "' ";
					} else if (field.toString().startsWith("!%")) {
						sql += " and "
								+ field.toString().substring(2)
								+ " not like '%"
								+ decodeSpecialCharsWhenLikeUseSlash(value
										.toString()) + "%' ";
					} else {
						sql += " and "
								+ field.toString()
								+ " like '%"
								+ decodeSpecialCharsWhenLikeUseSlash(value
										.toString()) + "%' ";
					}
				}
				sql += " order by " + orderByField + " " + orderByValue
						+ " limit ?,? ";
			}
			// System.out.println("sql=" + sql);

			// 执行sql语句
			Connection conn = null;
			PreparedStatement ps = null;
			ResultSet rs = null;
			List<Map<String, Object>> r = new ArrayList<Map<String, Object>>();
			try {
				conn = DriverManager.getConnection(
						aShardingDataSource.getDbUrl(),
						aShardingDataSource.getDbUser(),
						aShardingDataSource.getDbPassword());

				ps = conn.prepareStatement(sql);
				ps.setInt(1, (pageNumber - 1) * pageSize);
				ps.setInt(2, pageSize);
				rs = ps.executeQuery();

				ResultSetMetaData data = rs.getMetaData();
				Map<String, Object> map = null;
				while (rs.next()) {
					map = new HashMap<String, Object>();
					for (int i = 1; i <= data.getColumnCount(); i++) {
						String columnName = data.getColumnLabel(i);
						if(rs.getObject(i) != null){
							map.put(columnName, UnicodeConverter.unicode2String(String.valueOf(rs.getObject(i))));
						}
					}
					r.add(map);
				}
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			} finally {
				// 关闭
				if (rs != null)
					try {
						rs.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				if (ps != null)
					try {
						ps.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				if (conn != null)
					try {
						conn.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				rs = null;
				ps = null;
				conn = null;
			}

			return r;

		} else {
			if (isMongodbstorage) {
				ESQueryBuilderConstructor constructor = new ESQueryBuilderConstructor();
				ESQueryBuilders aESQueryBuilders = null;
				if (conditions != null) {
					Iterator iter = conditions.entrySet().iterator();
					while (iter.hasNext()) {
						Map.Entry entry = (Map.Entry) iter.next();
						String key = entry.getKey().toString();
						String value = entry.getValue().toString();
						if (key.toString().startsWith("=")) {
							aESQueryBuilders.term(
									key.substring(1) + ".keyword", value);
						} else if (key.toString().startsWith("><")) {
							aESQueryBuilders.range(key.substring(2)
									+ ".keyword", value.split("#")[0],
									value.split("#")[1]);
						} else {
							aESQueryBuilders.match(key, value);
						}
					}
				}
				constructor.must(aESQueryBuilders);

				if ("desc".equals(orderByValue)) {
					constructor.setDesc(orderByField + ".keyword");
				} else if ("asc".equals(orderByValue)) {
					constructor.setAsc(orderByField + ".keyword");
				}
				constructor.setFrom((pageNumber - 1) * pageSize); // 分页查询条目起始位置，
																	// 默认0
				constructor.setSize(pageSize); // 查询返回条数，最大 10000
				List<Map<String, Object>> r = aElasticSearchService.search(mongoDbName,
						repositoryPrefix + "." + classesEn, constructor);
				return unicode2String(r);
			} else {
				if (conditions == null) {
					String sql = " select " + showField + " from "
							+ repositoryPrefix + "_" + classesEn;
					sql += " order by " + orderByField + " " + orderByValue;
					List<Map<String, Object>> r = super.selectPage(
							new Page(pageNumber, pageSize), sql, null)
							.getRecords();
					
					return unicode2String(r);
				} else {
					String sql = " select " + showField + " from "
							+ repositoryPrefix + "_" + classesEn
							+ " where 1=1 ";
					Iterator iter = conditions.entrySet().iterator();
					while (iter.hasNext()) {
						Map.Entry entry = (Map.Entry) iter.next();
						Object field = entry.getKey();
						Object value = entry.getValue();
						System.out.println(field + "/" + value);
						if (field.toString().startsWith("=")) {
							sql += " and "
									+ field.toString().substring(1)
									+ " = '"
									+ decodeSpecialCharsWhenLikeUseSlash(value
											.toString()) + "' ";
						} else if (field.toString().startsWith("><")) {
							sql += " and " + field.toString().substring(2)
									+ " >= '" + value.toString().split("#")[0]
									+ "' " + " and "
									+ field.toString().substring(2) + " <= '"
									+ value.toString().split("#")[1] + "' ";
						} else if (field.toString().startsWith("!%")) {
							sql += " and "
									+ field.toString().substring(2)
									+ " not like '%"
									+ decodeSpecialCharsWhenLikeUseSlash(value
											.toString()) + "%' ";
						} else {
							sql += " and "
									+ field.toString()
									+ " like '%"
									+ decodeSpecialCharsWhenLikeUseSlash(value
											.toString()) + "%' ";
						}
					}
					sql += " order by " + orderByField + " " + orderByValue;
					System.out.println("sql=" + sql);
					
					List<Map<String, Object>> r = super.selectPage(new Page(pageNumber, pageSize),sql, null).getRecords();

					return unicode2String(r);
				}
				//
			}
			//
		}
	}

	@Override
	public List<Map<String, Object>> getDynamicData(String classesEn,
			Map<String, Object> conditions, String orderByField,
			String orderByValue, int pageNumber, int pageSize,
			String shardingDataSourceId, String tableName) {

		if (orderByField == null || orderByValue == null) {
			orderByField = "create_time";
			orderByValue = "desc";
		}

		if (shardingDataSourceId != null && !"".equals(shardingDataSourceId)
				&& tableName != null && !"".equals(tableName)) {
			ShardingDataSource aShardingDataSource = publicService
					.findShardingDataSource(Integer
							.parseInt(shardingDataSourceId));

			if (conditions == null || conditions.size() == 0) {
				String sql = " select * from " + tableName;
				if ("id".equals(orderByField)) {
					sql += " order by id DESC";
				} else {
					sql += " order by id DESC," + orderByField + " "
							+ orderByValue;
				}
				sql += " limit ?,? ";
				// System.out.println("sql=" + sql);

				// 执行sql语句
				Connection conn = null;
				PreparedStatement ps = null;
				ResultSet rs = null;
				List<Map<String, Object>> r = new ArrayList<Map<String, Object>>();
				try {
					conn = DriverManager.getConnection(
							aShardingDataSource.getDbUrl(),
							aShardingDataSource.getDbUser(),
							aShardingDataSource.getDbPassword());

					ps = conn.prepareStatement(sql);
					ps.setInt(1, (pageNumber - 1) * pageSize);
					ps.setInt(2, pageSize);
					rs = ps.executeQuery();

					ResultSetMetaData data = rs.getMetaData();
					Map<String, Object> map = null;
					while (rs.next()) {
						map = new HashMap<String, Object>();
						for (int i = 1; i <= data.getColumnCount(); i++) {
							String columnName = data.getColumnLabel(i);
							if(rs.getObject(i) != null){
								map.put(columnName, UnicodeConverter.unicode2String(String.valueOf(rs.getObject(i))));
							}
						}
						r.add(map);
					}
				} catch (Exception e) {
					e.printStackTrace();
					return null;
				} finally {
					// 关闭
					if (rs != null)
						try {
							rs.close();
						} catch (SQLException e) {
							e.printStackTrace();
						}
					if (ps != null)
						try {
							ps.close();
						} catch (SQLException e) {
							e.printStackTrace();
						}
					if (conn != null)
						try {
							conn.close();
						} catch (SQLException e) {
							e.printStackTrace();
						}
					rs = null;
					ps = null;
					conn = null;
				}

				return r;

			} else {
				String sql = " select * from " + tableName + " where 1=1 ";
				Iterator iter = conditions.entrySet().iterator();
				while (iter.hasNext()) {
					Map.Entry entry = (Map.Entry) iter.next();
					Object field = entry.getKey();
					Object value = entry.getValue();
					// System.out.println(field + "/" + value);
					if (field.toString().startsWith("=")) {
						sql += " and "
								+ field.toString().substring(1)
								+ " = '"
								+ decodeSpecialCharsWhenLikeUseSlash(value
										.toString()) + "' ";
					} else if (field.toString().startsWith("><")) {
						sql += " and " + field.toString().substring(2)
								+ " >= '" + value.toString().split("#")[0]
								+ "' " + " and "
								+ field.toString().substring(2) + " <= '"
								+ value.toString().split("#")[1] + "' ";
					} else if (field.toString().startsWith("!%")) {
						sql += " and "
								+ field.toString().substring(2)
								+ " not like '%"
								+ decodeSpecialCharsWhenLikeUseSlash(value
										.toString()) + "%' ";
					}else {
						sql += " and "
								+ field.toString()
								+ " like '%"
								+ decodeSpecialCharsWhenLikeUseSlash(value
										.toString()) + "%' ";
					}
				}
				if ("id".equals(orderByField)) {
					sql += " order by id DESC";
				} else {
					sql += " order by id DESC," + orderByField + " "
							+ orderByValue;
				}
				sql += " limit ?,? ";
				System.out.println("sql=" + sql);

				// 执行sql语句
				Connection conn = null;
				PreparedStatement ps = null;
				ResultSet rs = null;
				List<Map<String, Object>> r = new ArrayList<Map<String, Object>>();
				try {
					conn = DriverManager.getConnection(
							aShardingDataSource.getDbUrl(),
							aShardingDataSource.getDbUser(),
							aShardingDataSource.getDbPassword());

					ps = conn.prepareStatement(sql);
					ps.setInt(1, (pageNumber - 1) * pageSize);
					ps.setInt(2, pageSize);
					rs = ps.executeQuery();

					ResultSetMetaData data = rs.getMetaData();
					Map<String, Object> map = null;
					while (rs.next()) {
						map = new HashMap<String, Object>();
						for (int i = 1; i <= data.getColumnCount(); i++) {
							String columnName = data.getColumnLabel(i);
							if(rs.getObject(i) != null){
								map.put(columnName, UnicodeConverter.unicode2String(String.valueOf(rs.getObject(i))));
							}
						}
						r.add(map);
					}
				} catch (Exception e) {
					e.printStackTrace();
					return null;
				} finally {
					// 关闭
					if (rs != null)
						try {
							rs.close();
						} catch (SQLException e) {
							e.printStackTrace();
						}
					if (ps != null)
						try {
							ps.close();
						} catch (SQLException e) {
							e.printStackTrace();
						}
					if (conn != null)
						try {
							conn.close();
						} catch (SQLException e) {
							e.printStackTrace();
						}
					rs = null;
					ps = null;
					conn = null;
				}

				return r;

			}
			//
		} else {
			if (isMongodbstorage) {
				ESQueryBuilderConstructor constructor = new ESQueryBuilderConstructor();
				ESQueryBuilders aESQueryBuilders = null;
				if (conditions != null) {
					aESQueryBuilders = new ESQueryBuilders();
					Iterator iter = conditions.entrySet().iterator();
					while (iter.hasNext()) {
						Map.Entry entry = (Map.Entry) iter.next();
						String key = entry.getKey().toString();
						String value = entry.getValue().toString();
						if (key.toString().startsWith("=")) {
							aESQueryBuilders.term(
									key.substring(1) + ".keyword", value);
						} else if (key.toString().startsWith("><")) {
							aESQueryBuilders.range(key.substring(2)
									+ ".keyword", value.split("#")[0],
									value.split("#")[1]);
						} else {
							aESQueryBuilders.match(key, value);
						}
						//
					}
				}
				constructor.must(aESQueryBuilders);

				if ("desc".equals(orderByValue)) {
					constructor.setDesc(orderByField + ".keyword");
				} else if ("asc".equals(orderByValue)) {
					constructor.setAsc(orderByField + ".keyword");
				}

				constructor.setFrom((pageNumber - 1) * pageSize); // 分页查询条目起始位置，
																	// 默认0
				constructor.setSize(pageSize); // 查询返回条数，最大 10000
				List<Map<String, Object>> r = aElasticSearchService.search(mongoDbName,
						repositoryPrefix + "." + classesEn, constructor);
				
				return unicode2String(r);
			} else {
				if (conditions == null) {
					String sql = " select * from " + repositoryPrefix + "_"
							+ classesEn;
					if ("id".equals(orderByField)) {
						sql += " order by id DESC";
					} else {
						sql += " order by id DESC," + orderByField + " "
								+ orderByValue;
					}
					List<Map<String, Object>> r = super.selectPage(
							new Page(pageNumber, pageSize), sql, null)
							.getRecords();
					
					return unicode2String(r);
				} else {
					String sql = " select * from " + repositoryPrefix + "_"
							+ classesEn + " where 1=1 ";
					Iterator iter = conditions.entrySet().iterator();
					while (iter.hasNext()) {
						Map.Entry entry = (Map.Entry) iter.next();
						Object field = entry.getKey();
						Object value = entry.getValue();
						// System.out.println(field + "/" + value);
						if (field.toString().startsWith("=")) {
							sql += " and "
									+ field.toString().substring(1)
									+ " = '"
									+ decodeSpecialCharsWhenLikeUseSlash(value
											.toString()) + "' ";
						} else if (field.toString().startsWith("><")) {
							sql += " and " + field.toString().substring(2)
									+ " >= '" + value.toString().split("#")[0]
									+ "' " + " and "
									+ field.toString().substring(2) + " <= '"
									+ value.toString().split("#")[1] + "' ";
						} else if (field.toString().startsWith("!%")) {
							sql += " and "
									+ field.toString().substring(2)
									+ " not like '%"
									+ decodeSpecialCharsWhenLikeUseSlash(value
											.toString()) + "%' ";
						}else if (field.toString().startsWith("!Null")){
							sql += " and "
									+ field.toString().substring(6)
									+ "<> ''";
						}else if (field.toString().startsWith("Null")){
							sql += " and "
									+ field.toString().substring(5)
									+ " ='' ";
						} else {
							sql += " and "
									+ field.toString()
									+ " like '%"
									+ decodeSpecialCharsWhenLikeUseSlash(value
											.toString()) + "%' ";
						}
					}
					if ("id".equals(orderByField)) {
						sql += " order by id DESC";
					} else {
						sql += " order by id DESC," + orderByField + " "
								+ orderByValue;
					}
					// System.out.println("sql=" + sql);
					//System.out.println("开始--"+DateUtils.getDateTime());
					//List<Map<String, Object>> r = super.selectPage(new Page(pageNumber, pageSize),sql, null).getRecords();
					List<Map<String, Object>> r = getSqlDynamicData(sql, pageNumber, pageSize);
					//System.out.println("结束--"+DateUtils.getDateTime());
					return unicode2String(r);
				}
			}
			//
		}
	}
	public List<Map<String, Object>> getSqlDynamicData(String sql,int pageNumber, int pageSize) {

		
			sql = sql + " limit "+(pageNumber-1)+", "+ pageSize;

			// 执行sql语句
			Connection conn = null;
			PreparedStatement ps = null;
			ResultSet rs = null;
			List<Map<String, Object>> r = new ArrayList<Map<String, Object>>();
			try {
				conn = DriverManager.getConnection(
						XxlConfClient.get("dal.jdbc.url", ""),
						XxlConfClient.get("dal.jdbc.username", "root"),
						XxlConfClient.get("dal.jdbc.password", ""));

				ps = conn.prepareStatement(sql);
				rs = ps.executeQuery();

				ResultSetMetaData data = rs.getMetaData();
				Map<String, Object> map = null;
				while (rs.next()) {
					map = new HashMap<String, Object>();
					for (int i = 1; i <= data.getColumnCount(); i++) {
						String columnName = data.getColumnLabel(i);
						if(rs.getObject(i) != null){
							map.put(columnName, UnicodeConverter.unicode2String(String.valueOf(rs.getObject(i))));
						}
					}
					r.add(map);
				}
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			} finally {
				// 关闭
				if (rs != null)
					try {
						rs.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				if (ps != null)
					try {
						ps.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				if (conn != null)
					try {
						conn.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				rs = null;
				ps = null;
				conn = null;
			}

			return r;
		}
	@Override
	public List<Map<String, Object>> getDynamicData(String classesEn,
			String id, int pageSize, String shardingDataSourceId,
			String tableName) {

		if (shardingDataSourceId != null && !"".equals(shardingDataSourceId)
				&& tableName != null && !"".equals(tableName)) {
			ShardingDataSource aShardingDataSource = publicService
					.findShardingDataSource(Integer
							.parseInt(shardingDataSourceId));

			String sql = "SELECT * from " + tableName + " where id >'" + id
					+ "' order by id asc limit " + (pageSize);

			// 执行sql语句
			Connection conn = null;
			PreparedStatement ps = null;
			ResultSet rs = null;
			List<Map<String, Object>> r = new ArrayList<Map<String, Object>>();
			try {
				conn = DriverManager.getConnection(
						aShardingDataSource.getDbUrl(),
						aShardingDataSource.getDbUser(),
						aShardingDataSource.getDbPassword());

				ps = conn.prepareStatement(sql);
				rs = ps.executeQuery();

				ResultSetMetaData data = rs.getMetaData();
				Map<String, Object> map = null;
				while (rs.next()) {
					map = new HashMap<String, Object>();
					for (int i = 1; i <= data.getColumnCount(); i++) {
						String columnName = data.getColumnLabel(i);
						if(rs.getObject(i) != null){
							map.put(columnName, UnicodeConverter.unicode2String(String.valueOf(rs.getObject(i))));
						}
					}
					r.add(map);
				}
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			} finally {
				// 关闭
				if (rs != null)
					try {
						rs.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				if (ps != null)
					try {
						ps.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				if (conn != null)
					try {
						conn.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				rs = null;
				ps = null;
				conn = null;
			}

			return r;
		} else {
			Connection conn = null;
			List<Map<String, Object>> listMap = null;
			try {
				conn = DriverManager.getConnection(
						XxlConfClient.get("dal.jdbc.url", ""),
						XxlConfClient.get("dal.jdbc.username", "root"),
						XxlConfClient.get("dal.jdbc.password", ""));

				String sql = "SELECT * from " + repositoryPrefix + "_"
						+ classesEn + " where id >'" + id
						+ "' order by id asc limit " + (pageSize);
				listMap = JdbcUtils.getListMap(conn, sql);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return unicode2String(listMap);
		}
		//
	}

	@Override
	public Long getDynamicCount(String classesEn,
			Map<String, Object> conditions, String shardingDataSourceId,
			String tableName) {
		if (shardingDataSourceId != null && !"".equals(shardingDataSourceId)
				&& tableName != null && !"".equals(tableName)) {
			ShardingDataSource aShardingDataSource = publicService
					.findShardingDataSource(Integer
							.parseInt(shardingDataSourceId));

			String sql = "";

			if (conditions == null || conditions.size() == 0) {
				sql = " select count(id) from " + tableName;
			} else {
				sql = " select count(1) from " + tableName + " where 1=1 ";
				Iterator iter = conditions.entrySet().iterator();
				while (iter.hasNext()) {
					Map.Entry entry = (Map.Entry) iter.next();
					Object field = entry.getKey();
					Object value = entry.getValue();
					if (field.toString().startsWith("=")) {
						sql += " and "
								+ field.toString().substring(1)
								+ " = '"
								+ decodeSpecialCharsWhenLikeUseSlash(value
										.toString()) + "' ";
					} else if (field.toString().startsWith("><")) {
						sql += " and " + field.toString().substring(2)
								+ " >= '" + value.toString().split("#")[0]
								+ "' " + " and "
								+ field.toString().substring(2) + " <= '"
								+ value.toString().split("#")[1] + "' ";
					} else if (field.toString().startsWith("!%")) {
						sql += " and "
								+ field.toString().substring(2)
								+ " not like '%"
								+ decodeSpecialCharsWhenLikeUseSlash(value
										.toString()) + "%' ";
					} else if (field.toString().startsWith(">=")) {
						sql += " and "
								+ field.toString().substring(2)
								+ " >= '"
								+ decodeSpecialCharsWhenLikeUseSlash(value
										.toString()) + "' ";
					} else {
						sql += " and "
								+ field.toString()
								+ " like '%"
								+ decodeSpecialCharsWhenLikeUseSlash(value
										.toString()) + "%' ";
					}

				}
			}
			//

			// 执行sql语句
			Connection conn = null;
			PreparedStatement ps = null;
			ResultSet rs = null;
			long dataCount = 0l;

			try {
				conn = DriverManager.getConnection(
						aShardingDataSource.getDbUrl(),
						aShardingDataSource.getDbUser(),
						aShardingDataSource.getDbPassword());

				ps = conn.prepareStatement(sql);
				rs = ps.executeQuery();
				if (rs.next()) {
					dataCount = rs.getLong(1);
				}

			} catch (Exception e) {
				e.printStackTrace();
				return 0l;
			} finally {
				// 关闭
				if (rs != null)
					try {
						rs.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				if (ps != null)
					try {
						ps.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				if (conn != null)
					try {
						conn.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				rs = null;
				ps = null;
				conn = null;
			}
			return dataCount;
		} else {
			if (isMongodbstorage) {

				ESQueryBuilderConstructor constructor = new ESQueryBuilderConstructor();
				ESQueryBuilders aESQueryBuilders = null;
				if (conditions != null) {
					aESQueryBuilders = new ESQueryBuilders();
					Iterator iter = conditions.entrySet().iterator();
					while (iter.hasNext()) {
						Map.Entry entry = (Map.Entry) iter.next();
						String key = entry.getKey().toString();
						String value = entry.getValue().toString();
						if (key.toString().startsWith("=")) {
							aESQueryBuilders.term(
									key.substring(1) + ".keyword", value);
						} else if (key.toString().startsWith("><")) {
							aESQueryBuilders.range(key.substring(2)
									+ ".keyword", value.split("#")[0],
									value.split("#")[1]);
						} else {
							aESQueryBuilders.match(key, value);
						}
						//
					}
				}
				constructor.must(aESQueryBuilders);
				return aElasticSearchService.searchCount(mongoDbName,
						repositoryPrefix + "." + classesEn, constructor);

			} else {
				if (conditions == null) {
					String sql = " select count(id) from " + repositoryPrefix
							+ "_" + classesEn;
					// 执行sql语句
					Connection conn = null;
					PreparedStatement ps = null;
					ResultSet rs = null;
					long dataCount = 0l;

					try {
						conn = DriverManager.getConnection(
								jdbcUrl,
								jdbcUserName,
								jdbcPassWord);

						ps = conn.prepareStatement(sql);
						rs = ps.executeQuery();
						if (rs.next()) {
							dataCount = rs.getLong(1);
						}

					} catch (Exception e) {
						e.printStackTrace();
						return 0l;
					} finally {
						// 关闭
						if (rs != null)
							try {
								rs.close();
							} catch (SQLException e) {
								e.printStackTrace();
							}
						if (ps != null)
							try {
								ps.close();
							} catch (SQLException e) {
								e.printStackTrace();
							}
						if (conn != null)
							try {
								conn.close();
							} catch (SQLException e) {
								e.printStackTrace();
							}
						rs = null;
						ps = null;
						conn = null;
					}
					//return Long.parseLong(super.selectCount(sql, null) + "");
					return dataCount;
				} else {
					String sql = " select count(1) from " + repositoryPrefix
							+ "_" + classesEn + " where 1=1 ";
					Iterator iter = conditions.entrySet().iterator();
					while (iter.hasNext()) {
						Map.Entry entry = (Map.Entry) iter.next();
						Object field = entry.getKey();
						Object value = entry.getValue();
						// System.out.println(field + "/" + value);
						if (field.toString().startsWith("=")) {
							sql += " and "
									+ field.toString().substring(1)
									+ " = '"
									+ decodeSpecialCharsWhenLikeUseSlash(value
											.toString()) + "' ";
						} else if (field.toString().startsWith("><")) {
							sql += " and " + field.toString().substring(2)
									+ " >= '" + value.toString().split("#")[0]
									+ "' " + " and "
									+ field.toString().substring(2) + " <= '"
									+ value.toString().split("#")[1] + "' ";
						} else if (field.toString().startsWith("!%")) {
							sql += " and "
									+ field.toString().substring(2)
									+ " not like '%"
									+ decodeSpecialCharsWhenLikeUseSlash(value
											.toString()) + "%' ";
						} else if (field.toString().startsWith(">=")) {
							sql += " and "
									+ field.toString().substring(2)
									+ " >= '"
									+ decodeSpecialCharsWhenLikeUseSlash(value
											.toString()) + "' ";
						}else if (field.toString().startsWith("!Null")){
								sql += " and "
										+ field.toString().substring(6)
										+ "<> ''";
							}else if (field.toString().startsWith("Null")){
								sql += " and "
										+ field.toString().substring(5)
										+ " ='' ";
						} else {
							sql += " and "
									+ field.toString()
									+ " like '%"
									+ decodeSpecialCharsWhenLikeUseSlash(value
											.toString()) + "%' ";
						}

					}
					// 执行sql语句
					Connection conn = null;
					PreparedStatement ps = null;
					ResultSet rs = null;
					long dataCount = 0l;

					try {
						conn = DriverManager.getConnection(
								jdbcUrl,
								jdbcUserName,
								jdbcPassWord);

						ps = conn.prepareStatement(sql);
						rs = ps.executeQuery();
						if (rs.next()) {
							dataCount = rs.getLong(1);
						}

					} catch (Exception e) {
						e.printStackTrace();
						return 0l;
					} finally {
						// 关闭
						if (rs != null)
							try {
								rs.close();
							} catch (SQLException e) {
								e.printStackTrace();
							}
						if (ps != null)
							try {
								ps.close();
							} catch (SQLException e) {
								e.printStackTrace();
							}
						if (conn != null)
							try {
								conn.close();
							} catch (SQLException e) {
								e.printStackTrace();
							}
						rs = null;
						ps = null;
						conn = null;
					}
					return dataCount;
					//return Long.parseLong(super.selectCount(sql, null) + "");
				}
			}
		}
	}

	@Override
	public Long getDynamicCount(String classesEn, String createUserId,
			String startTime, String endTime, String shardingDataSourceId,
			String tableName) {

		if (shardingDataSourceId != null && !"".equals(shardingDataSourceId)
				&& tableName != null && !"".equals(tableName)) {
			ShardingDataSource aShardingDataSource = publicService
					.findShardingDataSource(Integer
							.parseInt(shardingDataSourceId));

			// 执行sql语句
			Connection conn = null;
			PreparedStatement ps = null;
			ResultSet rs = null;
			long dataCount = 0l;

			try {
				conn = DriverManager.getConnection(
						aShardingDataSource.getDbUrl(),
						aShardingDataSource.getDbUser(),
						aShardingDataSource.getDbPassword());

				String sql = " select count(id) from "
						+ tableName
						+ " where create_user_id=? and create_time>=? and create_time<=? ";

				ps = conn.prepareStatement(sql);
				ps.setString(1, createUserId);
				ps.setString(2, startTime);
				ps.setString(3, endTime);

				rs = ps.executeQuery();
				if (rs.next()) {
					dataCount = rs.getLong(1);
				}

			} catch (Exception e) {
				e.printStackTrace();
				return 0l;
			} finally {
				// 关闭
				if (rs != null)
					try {
						rs.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				if (ps != null)
					try {
						ps.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				if (conn != null)
					try {
						conn.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				rs = null;
				ps = null;
				conn = null;
			}
			return dataCount;

		} else {

			if (isMongodbstorage) {

				ESQueryBuilderConstructor constructor = new ESQueryBuilderConstructor();
				ESQueryBuilders aESQueryBuilders = new ESQueryBuilders();
				if (createUserId != null && !"".equals(createUserId)) {
					aESQueryBuilders.term("create_user_id", createUserId);
				}
				if (startTime != null && !"".equals(startTime)) {
					aESQueryBuilders.range("create_time", startTime, endTime);
				}
				constructor.must(aESQueryBuilders);
				return aElasticSearchService.searchCount(mongoDbName,
						repositoryPrefix + "." + classesEn, constructor);

			} else {
				String sql = " select count(id) from "
						+ repositoryPrefix
						+ "_"
						+ classesEn
						+ " where create_user_id={0} and create_time>={1} and create_time<={2}";
				return Long.parseLong(super.selectCount(sql, new Object[] {
						createUserId, startTime, endTime })
						+ "");
			}
			//
		}

	}

	@Override
	public void saveDynamicObjectDataST(String classesEn, String id,
			String relevanceClassesEn, String relevanceId,
			Integer objectPropertyId, String createTime, String createUserId,
			String sourceShardingDataSourceId,
			String sourceTableName,
			String targetShardingDataSourceId, 
			String targetTableName) {

		ObjectProperty aObjectProperty = publicService
				.findObjectProperty(objectPropertyId);
		User aUser = publicService.findUser(Integer.parseInt(createUserId));

		if (sourceShardingDataSourceId != null
				&& !"".equals(sourceShardingDataSourceId)
				&& sourceTableName != null && !"".equals(sourceTableName)) {

			ShardingDataSource aShardingDataSource = publicService
					.findShardingDataSource(Integer
							.parseInt(sourceShardingDataSourceId));

			// 执行sql语句
			Connection conn = null;
			PreparedStatement ps = null;
			ResultSet rs = null;
			long dataCount = 0l;

			try {
				conn = DriverManager.getConnection(
						aShardingDataSource.getDbUrl(),
						aShardingDataSource.getDbUser(),
						aShardingDataSource.getDbPassword());

				String sql = "";
				String userOrgId = "";
				if (aUser != null) {
					userOrgId = aUser.getDepartmentId().toString();
				}
				String opId = String.valueOf(aIdWorker.nextId());

				sql += " insert into "
						+ sourceTableName
						+ "_"
						+ aObjectProperty.getNameEn()
						+ "( id,create_time,create_user_id, create_org_id, source_data_id,source_class_en,"
						+ "target_data_id,target_class_en,source_table_name,target_table_name,source_sharding_data_source_id,target_sharding_data_source_id ) "
						+ " values (?,?,?,?,?,?,?,?,?,?,?,?) ";

				// System.out.println("sql=" + sql);

				ps = conn.prepareStatement(sql);
				ps.setString(1, opId);
				ps.setString(2, createTime);
				ps.setString(3, createUserId);
				ps.setString(4, userOrgId);
				ps.setString(5, id);
				ps.setString(6, classesEn);
				ps.setString(7, relevanceId);
				ps.setString(8, relevanceClassesEn);
				ps.setString(9, sourceTableName);
				ps.setString(10, targetTableName);
				ps.setString(11, sourceShardingDataSourceId);
				ps.setString(12, targetShardingDataSourceId);

				ps.executeUpdate();

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				// 关闭
				if (rs != null)
					try {
						rs.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				if (ps != null)
					try {
						ps.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				if (conn != null)
					try {
						conn.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				rs = null;
				ps = null;
				conn = null;
			}

		} else {
			if (isMongodbstorage) {
				Document document = new Document();
				String opId = String.valueOf(aIdWorker.nextId());
				document.put("id", opId); // 主键ID
				if (createTime != null && !"".equals(createTime)) {
					document.put("create_time", createTime);
				}
				document.put("create_user_id", createUserId);
				if (aUser != null) {
					document.put("create_org_id", aUser.getDepartmentId() + "");
				}
				document.put("source_data_id", id);
				document.put("source_class_en", classesEn);
				document.put("target_data_id", relevanceId);
				document.put("target_class_en", relevanceClassesEn);

				MongoClientUtils.insertOne(aMongoDatabase, repositoryPrefix
						+ "." + classesEn + "." + aObjectProperty.getNameEn(),
						document);
			} else {
				
				//需要判断关联表是否分库分表 target_table_name,target_sharding_data_source_id
				if (targetShardingDataSourceId != null
						&& !"".equals(targetShardingDataSourceId)
						&& targetTableName != null && !"".equals(targetTableName)) {
					String sql = "";
					String userOrgId = "";
					if (aUser != null) {
						userOrgId = aUser.getDepartmentId().toString();
					}
					String opId = String.valueOf(aIdWorker.nextId());

					sql += " insert into " + repositoryPrefix + "_" + classesEn
							+ "_" + aObjectProperty.getNameEn() + "( ";

					// 通用字段
					sql += " id,create_time,create_user_id, create_org_id, source_data_id,source_class_en,target_data_id,target_class_en,target_table_name,target_sharding_data_source_id ) " 
					+ " values ({0},{1},{2},{3},{4},{5},{6},{7},{8},{9}) ";

					System.out.println("sql=" + sql);
					String[] parms = new String[] { opId, createTime, createUserId,
							userOrgId, id, classesEn, relevanceId,
							relevanceClassesEn, targetTableName, targetShardingDataSourceId };
					boolean b = super.insert(sql, parms);
					System.out.println("新增关联表数据SQL执行返回结果集:" + b);
					
					
				}else {
					String sql = "";
					String userOrgId = "";
					if (aUser != null) {
						userOrgId = aUser.getDepartmentId().toString();
					}
					String opId = String.valueOf(aIdWorker.nextId());

					sql += " insert into " + repositoryPrefix + "_" + classesEn
							+ "_" + aObjectProperty.getNameEn() + "( ";

					// 通用字段
					sql += " id,create_time,create_user_id, create_org_id, source_data_id,source_class_en,target_data_id,target_class_en ) values ({0},{1},{2},{3},{4},{5},{6},{7}) ";

					System.out.println("sql=" + sql);
					String[] parms = new String[] { opId, createTime, createUserId,
							userOrgId, id, classesEn, relevanceId,
							relevanceClassesEn };
					boolean b = super.insert(sql, parms);
					System.out.println("新增关联表数据SQL执行返回结果集:" + b);
				}
				//
			}
			//
		}
	}

	@Override
	public void deleteDynamicObjectData(String classesEn, String id,
			Integer objectPropertyId, String shardingDataSourceId,
			String tableName) {
		ObjectProperty aObjectProperty = publicService
				.findObjectProperty(objectPropertyId);
		if (shardingDataSourceId != null && !"".equals(shardingDataSourceId)
				&& tableName != null && !"".equals(tableName)) {
			ShardingDataSource aShardingDataSource = publicService
					.findShardingDataSource(Integer
							.parseInt(shardingDataSourceId));

			// 执行sql语句
			Connection conn = null;
			PreparedStatement ps = null;
			ResultSet rs = null;
			long dataCount = 0l;

			try {
				conn = DriverManager.getConnection(
						aShardingDataSource.getDbUrl(),
						aShardingDataSource.getDbUser(),
						aShardingDataSource.getDbPassword());

				String sql = " delete from " + tableName + "_"
						+ aObjectProperty.getNameEn() + " where id=? ";

				ps = conn.prepareStatement(sql);
				ps.setString(1, id);

				ps.executeUpdate();

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				// 关闭
				if (rs != null)
					try {
						rs.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				if (ps != null)
					try {
						ps.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				if (conn != null)
					try {
						conn.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				rs = null;
				ps = null;
				conn = null;
			}

		} else {
			if (isMongodbstorage) {
				MongoClientUtils.delete(aMongoDatabase, repositoryPrefix + "."
						+ classesEn + "." + aObjectProperty.getNameEn(), id);
			} else {
				String sql = " delete from " + repositoryPrefix + "_"
						+ classesEn + "_" + aObjectProperty.getNameEn()
						+ " where id={0} ";
				super.delete(sql, new Object[] { id });
			}
		}
	}

	@Override
	public Long getDynamicObjectDataCount(String classesEn, String sourceId,
			String targetId, Integer objectPropertyId,
			String shardingDataSourceId, String tableName) {

		ObjectProperty aObjectProperty = publicService
				.findObjectProperty(objectPropertyId);

		if (shardingDataSourceId != null && !"".equals(shardingDataSourceId)
				&& tableName != null && !"".equals(tableName)) {
			ShardingDataSource aShardingDataSource = publicService
					.findShardingDataSource(Integer
							.parseInt(shardingDataSourceId));

			// 执行sql语句
			Connection conn = null;
			PreparedStatement ps = null;
			ResultSet rs = null;
			long dataCount = 0l;

			try {
				conn = DriverManager.getConnection(
						aShardingDataSource.getDbUrl(),
						aShardingDataSource.getDbUser(),
						aShardingDataSource.getDbPassword());

				String sql = " select count(id) from " + tableName + "_"
						+ aObjectProperty.getNameEn() + " where 1=1 ";
				if (sourceId != null && !"".equals(sourceId)) {
					sql += " and source_data_id= '" + sourceId + "'";
				}
				if (targetId != null && !"".equals(targetId)) {
					sql += " and target_data_id= '" + targetId + "'";
				}

				ps = conn.prepareStatement(sql);
				rs = ps.executeQuery();
				if (rs.next()) {
					dataCount = rs.getLong(1);
				}
			} catch (Exception e) {
				e.printStackTrace();
				return 0l;
			} finally {
				// 关闭
				if (rs != null)
					try {
						rs.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				if (ps != null)
					try {
						ps.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				if (conn != null)
					try {
						conn.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				rs = null;
				ps = null;
				conn = null;
			}

			return dataCount;

		} else {
			if (isMongodbstorage) {
				ESQueryBuilderConstructor constructor = new ESQueryBuilderConstructor();
				ESQueryBuilders aESQueryBuilders = new ESQueryBuilders();
				if (sourceId != null && !"".equals(sourceId)) {
					aESQueryBuilders.term("source_data_id", sourceId);
				}
				if (targetId != null && !"".equals(targetId)) {
					aESQueryBuilders.term("target_data_id", targetId);
				}
				constructor.must(aESQueryBuilders);
				return aElasticSearchService.searchCount(mongoDbName,
						repositoryPrefix + "." + classesEn + "."
								+ aObjectProperty.getNameEn(), constructor);
			} else {
				String sql = " select count(id) from " + repositoryPrefix + "_"
						+ classesEn + "_" + aObjectProperty.getNameEn()
						+ " where 1=1 ";
				if (sourceId != null && !"".equals(sourceId)) {
					sql += " and source_data_id= '" + sourceId + "'";
				}
				if (targetId != null && !"".equals(targetId)) {
					sql += " and target_data_id= '" + targetId + "'";
				}
				return Long.parseLong(super.selectCount(sql, null) + "");
			}
			//
		}
	}

	@Override
	public List<Map<String, Object>> getDynamicObjectData(String classesEn,
			String sourceId, String targetId, Integer objectPropertyId,
			int pageNumber, int pageSize, String shardingDataSourceId,
			String tableName) {

		ObjectProperty aObjectProperty = publicService
				.findObjectProperty(objectPropertyId);

		if (shardingDataSourceId != null && !"".equals(shardingDataSourceId)
				&& tableName != null && !"".equals(tableName)) {
			ShardingDataSource aShardingDataSource = publicService
					.findShardingDataSource(Integer
							.parseInt(shardingDataSourceId));

			// 执行sql语句
			Connection conn = null;
			PreparedStatement ps = null;
			ResultSet rs = null;
			List<Map<String, Object>> r = new ArrayList<Map<String, Object>>();
			try {
				conn = DriverManager.getConnection(
						aShardingDataSource.getDbUrl(),
						aShardingDataSource.getDbUser(),
						aShardingDataSource.getDbPassword());

				String sql = " select * from " + tableName + "_"
						+ aObjectProperty.getNameEn() + " where 1=1 ";
				if (sourceId != null && !"".equals(sourceId)) {
					sql += " and source_data_id= '" + sourceId + "'";
				}
				if (targetId != null && !"".equals(targetId)) {
					sql += " and target_data_id= '" + targetId + "'";
				}
				sql += " order by create_time desc limit ?,? ";

				ps = conn.prepareStatement(sql);
				ps.setInt(1, (pageNumber - 1) * pageSize);
				ps.setInt(2, pageSize);
				rs = ps.executeQuery();

				ResultSetMetaData data = rs.getMetaData();
				Map<String, Object> map = null;
				while (rs.next()) {
					map = new HashMap<String, Object>();
					for (int i = 1; i <= data.getColumnCount(); i++) {
						String columnName = data.getColumnLabel(i);
						if(rs.getObject(i) != null){
							map.put(columnName, UnicodeConverter.unicode2String(String.valueOf(rs.getObject(i))));
						}
					}
					r.add(map);
				}
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			} finally {
				// 关闭
				if (rs != null)
					try {
						rs.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				if (ps != null)
					try {
						ps.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				if (conn != null)
					try {
						conn.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				rs = null;
				ps = null;
				conn = null;
			}

			return r;

		} else {
			if (isMongodbstorage) {
				ESQueryBuilderConstructor constructor = new ESQueryBuilderConstructor();
				ESQueryBuilders aESQueryBuilders = new ESQueryBuilders();
				if (sourceId != null && !"".equals(sourceId)) {
					aESQueryBuilders.term("source_data_id", sourceId);
				}
				if (targetId != null && !"".equals(targetId)) {
					aESQueryBuilders.term("target_data_id", targetId);
				}
				constructor.setDesc("create_time.keyword");
				constructor.setFrom((pageNumber - 1) * pageSize); // 分页查询条目起始位置，
																	// 默认0
				constructor.setSize(pageSize); // 查询返回条数，最大 10000
				constructor.must(aESQueryBuilders);
				List<Map<String, Object>> r = aElasticSearchService.search(mongoDbName,
						repositoryPrefix + "." + classesEn + "."
								+ aObjectProperty.getNameEn(), constructor);
				
				return unicode2String(r);
			} else {
				String sql = " select * from " + repositoryPrefix + "_"
						+ classesEn + "_" + aObjectProperty.getNameEn()
						+ " where 1=1 ";
				if (sourceId != null && !"".equals(sourceId)) {
					sql += " and source_data_id= '" + sourceId + "'";
				}
				if (targetId != null && !"".equals(targetId)) {
					sql += " and target_data_id= '" + targetId + "'";
				}
				sql += " order by create_time desc ";
				// System.out.println(sql);
				List<Map<String, Object>> r = super.selectPage(
						new Page(pageNumber, pageSize), sql, null).getRecords();
				return unicode2String(r);
			}
			//
		}
		//
	}

	@Override
	public List<SolrInputDocument> getIndexData(String classesEn,
			List<Map<String, Object>> list, String shardingDataSourceId,
			String tableName) {
		List<SolrInputDocument> r = new ArrayList<SolrInputDocument>();
		// 查询类
		HashMap<String, Object> queryParams = new HashMap<>();
		queryParams.put("=,nameEn", classesEn);
		List<Classes> classesList = publicService.getClasses(queryParams, 1, 1);
		Classes aClasses = null;
		if (classesList.size() > 0) {
			aClasses = classesList.get(0);
		} else {
			return null;
		}
		for (int k = 0; k < list.size(); k++) {
			Map<String, Object> data = list.get(k);
			// long startTime = System.currentTimeMillis();
			r.add(buildSolrInputDocument(data, aClasses, shardingDataSourceId,
					tableName));
			// long endTime = System.currentTimeMillis();
			// System.out.println("本组创建索引时间：" + (endTime - startTime) + "ms");
		}
		return r;
	}

	@Override
	public void submitDynamicData(String classesEn, String submitTime,
			String submitUserId, String shardingDataSourceId, String tableName) {

		User aUser = publicService.findUser(Integer.parseInt(submitUserId));

		// 删除类下所有索引
		// deleteIndexByClassesEn(classesEn);

		if (shardingDataSourceId != null && !"".equals(shardingDataSourceId)
				&& tableName != null && !"".equals(tableName)) {
			Map<String, Object> conditions = new HashMap<String, Object>();
			Long totalCount = getDynamicCount(classesEn, conditions,
					shardingDataSourceId, tableName);
			Long groupLenth = 10000l; // 每组记录数
			Long groupCount = totalCount / groupLenth; // 组数

			System.out.println("记录总数totalCount=" + totalCount);
			System.out.println("每组记录数groupLenth=" + groupLenth);
			System.out.println("待处理总组数groupCount=" + groupCount);

			for (int i = 0; i < groupCount; i++) {
				System.out.println("组数=" + (i + 1) + "/" + groupCount);
				long startTime = System.currentTimeMillis(); // 获取开始时间
				List<Map<String, Object>> list = getDynamicData(classesEn,
						null, null, null, (i + 1), groupLenth.intValue(),
						shardingDataSourceId, tableName);
				List<SolrInputDocument> indexList = getIndexData(classesEn,
						list, shardingDataSourceId, tableName);
				// 发布至solr
				submitIndex(indexList);
				long endTime = System.currentTimeMillis(); // 获取结束时间
				System.out.println("本组运行时间：" + (endTime - startTime) + "ms");
			}

			// 不足一整组
			if (totalCount % groupLenth > 0) {
				List<Map<String, Object>> list = getDynamicData(classesEn,
						null, null, null, (groupCount.intValue() + 1),
						groupLenth.intValue(), shardingDataSourceId, tableName);
				System.out.println("最后一组记录总数=" + totalCount.intValue()
						% groupLenth.intValue());
				List<SolrInputDocument> indexList = getIndexData(classesEn,
						list, shardingDataSourceId, tableName);
				// 发布至solr
				submitIndex(indexList);
				// 手动提交
				commitIndex();
			}
			//
		} else {
			// 结束代码 start
			if (isMongodbstorage) {

				Long totalCount = getDynamicCount(classesEn, null);
				Long groupLenth = 10000l; // 每组记录数
				Long groupCount = totalCount / groupLenth; // 组数

				System.out.println("总数totalCount=" + totalCount);
				System.out.println("每组记录数groupLenth=" + groupLenth);
				System.out.println("组数groupCount=" + groupCount);

				for (int i = 0; i < groupCount; i++) {
					System.out.println("groupCount=" + i + "/" + groupCount);
					List<Map<String, Object>> list = getDynamicData(classesEn,
							null, (i + 1), groupLenth.intValue());

					List<SolrInputDocument> indexList = getIndexData(classesEn,
							list);
					// 发布至solr
					submitIndex(indexList);
				}

				// 不足一整组
				if (totalCount % groupLenth > 0) {
					List<Map<String, Object>> list = getDynamicData(classesEn,
							null, (groupCount.intValue() + 1),
							groupLenth.intValue());
					List<SolrInputDocument> indexList = getIndexData(classesEn,
							list);
					// 发布至solr
					submitIndex(indexList);
					// 手动提交
					commitIndex();
				}

			} else {
				Long totalCount = getDynamicCount(classesEn, null);
				Long groupLenth = 10000l; // 每组记录数
				Long groupCount = totalCount / groupLenth; // 组数

				System.out.println("记录总数totalCount=" + totalCount);
				System.out.println("每组记录数groupLenth=" + groupLenth);
				System.out.println("待处理总组数groupCount=" + groupCount);

				for (int i = 0; i < groupCount; i++) {
					System.out.println("组数=" + (i + 1) + "/" + groupCount);
					long startTime = System.currentTimeMillis(); // 获取开始时间
					List<Map<String, Object>> list = getDynamicData(classesEn,
							null, (i + 1), groupLenth.intValue());
					List<SolrInputDocument> indexList = getIndexData(classesEn,
							list);
					// 发布至solr
					submitIndex(indexList);
					long endTime = System.currentTimeMillis(); // 获取结束时间
					System.out
							.println("本组运行时间：" + (endTime - startTime) + "ms");
				}

				// 不足一整组
				if (totalCount % groupLenth > 0) {
					List<Map<String, Object>> list = getDynamicData(classesEn,
							null, (groupCount.intValue() + 1),
							groupLenth.intValue());
					System.out.println("最后一组记录总数=" + totalCount.intValue()
							% groupLenth.intValue());
					List<SolrInputDocument> indexList = getIndexData(classesEn,
							list);
					// 发布至solr
					submitIndex(indexList);
					// 手动提交
					commitIndex();
				}
				//
			}
			// 结束代码 end
		}
		//
	}

	@Override
	public void submitCommitIndex(String classesEn,
			List<Map<String, Object>> list, String shardingDataSourceId,
			String tableName) {

		List<SolrInputDocument> indexData = getIndexData(classesEn, list,
				shardingDataSourceId, tableName);
		try {
			server.add(indexData);
			// server.commit(false, false);
			// commitIndex();
		} catch (Exception e) {
			LOG.error("批量创建索引失败.", e);
			e.printStackTrace();
		}
		//

	}

	@Override
	public void saveDynamicObjectDataT(String classesEn, String id,
			String relevanceClassesEn, String relevanceId,
			Integer objectPropertyId, String createTime, String createUserId,
			String targetShardingDataSourceId, String targetTableName) {
		saveDynamicObjectDataST(classesEn, id, relevanceClassesEn, relevanceId, objectPropertyId, createTime, createUserId, 
				null, null, targetShardingDataSourceId, targetTableName);
	}

	@Override
	public void saveDynamicObjectDataS(String classesEn, String id,
			String relevanceClassesEn, String relevanceId,
			Integer objectPropertyId, String createTime, String createUserId,
			String sourceShardingDataSourceId, String sourceTableName) {
		saveDynamicObjectDataST(classesEn, id, relevanceClassesEn, relevanceId, objectPropertyId, createTime, 
				createUserId, sourceShardingDataSourceId,sourceTableName,null, null);
	}

	@Override
	public Map<String,List<String>> getDynamicDataSqls(Classes sourceClasses,Classes targetClasses,
			String sourceTableName,String targetTableName,String opTableName,Map<String, Object> sourceData,
			List<Map<String, Object>> targetData,String sourceShardingDataSourceId,String targetShardingDataSourceId) {
		Map<String,List<String>> msqls = new HashMap<String, List<String>>();
		List<String>source_op_sqls = new ArrayList<String>();
		List<String>target_sql = new ArrayList<String>();
		HashMap<String, Object> queryParams = new HashMap<String, Object>();
		//主表
		String sql = "INSERT INTO " + sourceTableName + "(";
		String value = "VALUES('";
		for (String key : sourceData.keySet()) {
			sql += key + ",";
			if(sourceData.get(key) != null ){
				value += sourceData.get(key).toString() + "','";
			}else{
				value += sourceData.get(key) + "','";
			}
		}
		sql += "create_time,create_user_id,status,version,classes_id,data_source,create_org_id,";
		if(sql.endsWith(",")){
			sql = sql.substring(0,sql.lastIndexOf(",")) +")";
		} 
		value += DateUtils.getDateTime() + "','1','0','1.0','" + sourceClasses.getId() + "','" + 0 +"','48','";
		if(value.endsWith(",'")){
			value = value.substring(0,value.lastIndexOf(",")) +");";
		}
		source_op_sqls.add(sql + value);
		if(targetData == null){
			targetData = new ArrayList<Map<String,Object>>();
		}
		//关联表-从表
		for (int i = 0; i < targetData.size(); i++) {
			sql = "INSERT INTO " + targetTableName + "(";
			value = "VALUES('";
			for (String key : targetData.get(i).keySet()) {
				sql += key + ",";
				if(targetData.get(i).get(key) != null){
					value += targetData.get(i).get(key).toString() + "','";
				}else{
					value += targetData.get(i).get(key) + "','";
				}
			}
			sql += "create_time,create_user_id,status,version,classes_id,data_source,create_org_id,";
			if(sql.endsWith(",")){
				sql = sql.substring(0,sql.lastIndexOf(",")) +")";
			}
			value +=  DateUtils.getDateTime() + "','1','0','1.0','" + targetClasses.getId() + "','" + 0 +"','48','";
			if(value.endsWith(",'")){
				value = value.substring(0,value.lastIndexOf(",")) +");";
			}
			target_sql.add(sql + value);
		}
		//op表
		if(sourceShardingDataSourceId != null && !"".equals(sourceShardingDataSourceId)
				&& sourceTableName != null && !"".equals(sourceTableName)){//主表分表分库
			for (int i = 0; i < targetData.size(); i++) {
				sql = "INSERT INTO " + opTableName ;
				sql += "(id,create_time,create_user_id, create_org_id, source_data_id,source_class_en,"
					+ "target_data_id,target_class_en,source_table_name,target_table_name"
					+ ",source_sharding_data_source_id,target_sharding_data_source_id)";
				sql += "VALUES('" + aIdWorker.nextId() + "','" + DateUtils.getDateTime() + "','1','48','"
					+ sourceData.get("id") + "','" + sourceClasses.getNameEn() + "','"  + targetData.get(i).get("id") + "','" 
					+ targetClasses.getNameEn() + "','" + sourceTableName + "','" + targetTableName + "','" 
					+ sourceShardingDataSourceId + "','" + targetShardingDataSourceId + "');";
				source_op_sqls.add(sql);
			}
		}else{
			//关联表分库分表
			if(targetShardingDataSourceId != null && !"".equals(targetShardingDataSourceId)
					&& targetTableName != null && !"".equals(targetTableName)){
				for (int i = 0; i < targetData.size(); i++) {
					sql = "INSERT INTO " + opTableName ;
					sql += "(id,create_time,create_user_id, create_org_id, source_data_id,source_class_en,"
						+ "target_data_id,target_class_en,target_table_name,target_sharding_data_source_id)";
					sql += "VALUES('" + aIdWorker.nextId() + "','" + DateUtils.getDateTime() + "','1','48','"
						+ sourceData.get("id") + "','" + sourceClasses.getNameEn() + "','"  + targetData.get(i).get("id") + "','" 
						+ targetClasses.getNameEn() + "','" + targetTableName + "','" + targetShardingDataSourceId + "');";
					source_op_sqls.add(sql);
					
				}
			}else{
				for (int i = 0; i < targetData.size(); i++) {
					sql = "INSERT INTO " + opTableName ;
					sql += "(id,create_time,create_user_id, create_org_id, source_data_id,source_class_en,"
						+ "target_data_id,target_class_en)";
					sql += "VALUES('" + aIdWorker.nextId() + "','" + DateUtils.getDateTime() + "','1','48','"
						+ sourceData.get("id") + "','" + sourceClasses.getNameEn() + "','"  + targetData.get(i).get("id") + "','" 
						+ targetClasses.getNameEn() + "');";
					source_op_sqls.add(sql);
				}
			}
		}
		msqls.put("source", source_op_sqls);
		msqls.put("target", target_sql);
		return msqls;
	}
	@Override
	public Map<String, String> getDynamicMutilValueSqls(String sourceClassesEn, String targetClassesEn,
			String sourceTableName, String targetTableName, String opTableName, Map<String, Object> sourceData,
			List<Map<String, Object>> targetData, String sourceShardingDataSourceId,
			String targetShardingDataSourceId) {
		Map<String,String> msqls = new HashMap<String, String>();
		StringBuffer source_sqls = new StringBuffer();
		StringBuffer op_sqls = new StringBuffer();
		StringBuffer target_sqls= new StringBuffer();
		StringBuffer source_key = new StringBuffer();
		StringBuffer op_key = new StringBuffer();
		StringBuffer target_key= new StringBuffer();
		HashMap<String, Object> queryParams = new HashMap<String, Object>();
		
		//主表
		source_sqls.append("(");
		source_key.append("INSERT INTO ").append(sourceTableName).append("(");
		for (String key : sourceData.keySet()) {
			source_sqls.append("'").append(sourceData.get(key)).append("',");
			source_key.append(key).append(",");
		}
		source_sqls.deleteCharAt(source_sqls.length()-1);
		source_sqls.append("),");
		source_key.deleteCharAt(source_key.length()-1);
		source_key.append(") VALUES ");
		
		
		if(targetData == null){
			targetData = new ArrayList<Map<String,Object>>();
		}
		
		//关联表-从表
		for (int i = 0; i < targetData.size(); i++) {
			target_sqls.append("(");
			if(i == 0){
				target_key.append("INSERT INTO ").append(targetTableName).append("(");
			}
			for (String key : targetData.get(i).keySet()) {
				if(i == 0){
					target_key.append(key).append(",");
				}
				target_sqls.append("'").append(targetData.get(i).get(key)).append("',");
				
			}
			target_sqls.deleteCharAt(target_sqls.length()-1);
			target_sqls.append("),");
		}
		if(target_key.length()>0){
			target_key.deleteCharAt(target_key.length()-1).append(") VALUES ");
		}
		
		//op表
		if(sourceShardingDataSourceId != null && !"".equals(sourceShardingDataSourceId)
				&& sourceTableName != null && !"".equals(sourceTableName)){//主表分表分库
			op_key.append("INSERT INTO ").append(opTableName)
			.append("(id,create_time,create_user_id, create_org_id, source_data_id,source_class_en,")
			.append("target_data_id,target_class_en,source_table_name,target_table_name")
			.append(",source_sharding_data_source_id,target_sharding_data_source_id) VALUES ");
			for (int i = 0; i < targetData.size(); i++) {
				op_sqls.append("('").append(aIdWorker.nextId()).append("',");
				op_sqls.append("'").append(DateUtils.getDateTime()).append("',");
				op_sqls.append("'").append(1).append("',");
				op_sqls.append("'").append(48).append("',");
				op_sqls.append("'").append(sourceData.get("id")).append("',");
				op_sqls.append("'").append(sourceClassesEn).append("',");
				op_sqls.append("'").append(targetData.get(i).get("id")).append("',");
				op_sqls.append("'").append(targetClassesEn).append("',");
				op_sqls.append("'").append(sourceTableName).append("',");
				op_sqls.append("'").append(targetTableName).append("',");
				op_sqls.append("'").append(sourceShardingDataSourceId).append("',");
				op_sqls.append("'").append(targetShardingDataSourceId).append("'),");
			}
		}else{
			//关联表分库分表
			if(targetShardingDataSourceId != null && !"".equals(targetShardingDataSourceId)
					&& targetTableName != null && !"".equals(targetTableName)){
				op_key.append("INSERT INTO ").append(opTableName);
				op_key.append("(id,create_time,create_user_id, create_org_id, source_data_id,source_class_en,");
				op_key.append("target_data_id,target_class_en,target_table_name,target_sharding_data_source_id) VALUES ");
				for (int i = 0; i < targetData.size(); i++) {
					op_sqls.append("('").append(aIdWorker.nextId()).append("',");
					op_sqls.append("'").append(DateUtils.getDateTime()).append("',");
					op_sqls.append("'").append(1).append("',");
					op_sqls.append("'").append(48).append("',");
					op_sqls.append("'").append(targetData.get(i).get("id")).append("',");
					op_sqls.append("'").append(sourceData.get("id")).append("',");
					op_sqls.append("'").append(sourceClassesEn).append("',");
					op_sqls.append("'").append(targetClassesEn).append("',");
					op_sqls.append("'").append(targetTableName).append("',");
					op_sqls.append("'").append(targetShardingDataSourceId).append("'),");
				}
			}else{
				op_key.append("INSERT INTO ").append(opTableName);
				op_key.append("(id,create_time,create_user_id, create_org_id, source_data_id,source_class_en,");
				op_key.append("target_data_id,target_class_en) VALUES ");
				for (int i = 0; i < targetData.size(); i++) {
					op_sqls.append("('").append(aIdWorker.nextId()).append("',");
					op_sqls.append("'").append(DateUtils.getDateTime()).append("',");
					op_sqls.append("'").append(1).append("',");
					op_sqls.append("'").append(48).append("',");
					op_sqls.append("'").append(sourceData.get("id")).append("',");
					op_sqls.append("'").append(sourceClassesEn).append("',");
					op_sqls.append("'").append(targetData.get(i).get("id")).append("',");
					op_sqls.append("'").append(targetClassesEn).append("'),");
				}
			}
		}
		msqls.put("source_sqls", source_sqls.toString());
		msqls.put("target_sqls", target_sqls.toString());
		msqls.put("op_sqls", op_sqls.toString());
		msqls.put("source_key", source_key.toString());
		msqls.put("target_key", target_key.toString());
		msqls.put("op_key", op_key.toString());
		source_sqls = null;
		target_sqls = null;
		op_sqls = null;
		source_key = null;
		target_key = null;
		op_key = null;
		return msqls;
	}
	@Override
	public void batchSubmitDynamicDataSqls(String sourceClassesEn, String targetClassesEn,
			List<Map<String, Object>> sourceDataList, Map<String, List<Map<String, Object>>> targetDataList) {
		List<String>source_op_sqls=new ArrayList<String>();
		List<String>target_sql=new ArrayList<String>();
		
		HashMap<String, Object> sourceQueryParams = new HashMap<String, Object>();
		sourceQueryParams.put("=,classesEn", sourceClassesEn);
		Integer sourceShardingRepositoryCountCount = publicService.getShardingRepositoryCountCount(sourceQueryParams);
		HashMap<String, Object> targetQueryParams = new HashMap<String, Object>();
		targetQueryParams.put("=,classesEn", targetClassesEn);
		Integer targetShardingRepositoryCountCount = publicService.getShardingRepositoryCountCount(targetQueryParams);
		
		HashMap<String, Object> sourceClassQueryParams = new HashMap<String, Object>();
		HashMap<String, Object> targetClassQueryParams = new HashMap<String, Object>();
		sourceClassQueryParams.put("=,nameEn", sourceClassesEn);
		targetClassQueryParams.put("=,nameEn", targetClassesEn);
		List<Classes> sourceClasses = publicService.getClasses(sourceClassQueryParams, 1, 1);
		List<Classes> targetClasses = publicService.getClasses(targetClassQueryParams, 1, 1);
		
		String sourceTableName = null;
		String sourceShardingDataSourceId = null;
		String targetTableName = null;
		String targetShardingDataSourceId = null;
		String opNameEn = null;
		String opTableName = null;//op表名称
		
		ShardingDataSource sourceDataSource = null;//主表和op表数据源
		ShardingDataSource targetDataSource = null;//关联表数据源
		
		//op表
		List<ObjectProperty> objectProperty = publicService.getObjectProperty(sourceClasses.get(0));
		for (ObjectProperty o : objectProperty) {
			if(o.getRelevanceClassesId().equals(targetClasses.get(0).getId())){
				opNameEn = o.getNameEn();
				break;
			}
		}
		//主表
		if(sourceShardingRepositoryCountCount != null && sourceShardingRepositoryCountCount > 0){//分库分表
			List<ShardingRepositoryCount> shardingRepositoryCounts = publicService.getShardingRepositoryCount(sourceQueryParams, 1, sourceShardingRepositoryCountCount);
			List<ShardingRepositoryDataSource> shardingRepositoryDataSource = publicService.getShardingRepositoryDataSource(sourceQueryParams, 1, 1);//获取阈值
			for (int i = 0; i < sourceShardingRepositoryCountCount; i++) {
				if(shardingRepositoryCounts.get(i).getDataCount()<shardingRepositoryDataSource.get(0).getShardingThreshold()){
					sourceTableName = shardingRepositoryCounts.get(i).getTableName();
					sourceShardingDataSourceId = shardingRepositoryCounts.get(i).getShardingDataSourceId().toString();
					//op表名称
					opTableName = sourceTableName + "_" +  opNameEn;
					
					sourceDataSource = publicService.findShardingDataSource(Integer.parseInt(sourceShardingDataSourceId));
					break;
				}
			}
		}else{
			//op表名称
			opTableName = "hymax_" + sourceClassesEn + "_" +  opNameEn;
		}
		//从表
		if(targetShardingRepositoryCountCount != null && targetShardingRepositoryCountCount > 0){//分库分表
			List<ShardingRepositoryCount> shardingRepositoryCounts = publicService.getShardingRepositoryCount(targetQueryParams, 1, targetShardingRepositoryCountCount);
			List<ShardingRepositoryDataSource> shardingRepositoryDataSource = publicService.getShardingRepositoryDataSource(targetQueryParams, 1, 1);//获取阈值
			for (int i = 0; i < targetShardingRepositoryCountCount; i++) {
				if(shardingRepositoryCounts.get(i).getDataCount()<shardingRepositoryDataSource.get(0).getShardingThreshold()){
					targetTableName = shardingRepositoryCounts.get(i).getTableName();
					targetShardingDataSourceId = shardingRepositoryCounts.get(i).getShardingDataSourceId().toString();
					targetDataSource = publicService.findShardingDataSource(Integer.parseInt(targetShardingDataSourceId));
					break;
				}
			}
		}
		
		//分别存储主表op表和关联表
		
		for (Map<String, Object> map : sourceDataList) {
			List<Map<String, Object>> list = targetDataList.get(map.get("id").toString());
			Map<String, List<String>> dynamicDataSqls = getDynamicDataSqls(sourceClasses.get(0), targetClasses.get(0), sourceTableName, targetTableName, opTableName, map, list, sourceShardingDataSourceId, targetShardingDataSourceId);
			if(dynamicDataSqls.get("source") != null ){
				source_op_sqls.addAll(dynamicDataSqls.get("source"));
			}
			if(dynamicDataSqls.get("target") != null ){
				target_sql.addAll(dynamicDataSqls.get("target"));
			}
		}
		
		//************多值插入************
		/*
		StringBuffer source_sqls = new StringBuffer();
		StringBuffer op_sqls = new StringBuffer();
		StringBuffer target_sqls= new StringBuffer();
		StringBuffer source_key = new StringBuffer();
		StringBuffer op_key = new StringBuffer();
		StringBuffer target_key= new StringBuffer();
		int index = 0;
		for (Map<String, Object> map : sourceDataList) {
			List<Map<String, Object>> list = targetDataList.get(map.get("id").toString());
			Map<String, String> dynamicDataSqls = getDynamicMutilValueSqls(sourceClassesEn, targetClassesEn, sourceTableName, targetTableName, opTableName, map, list, sourceShardingDataSourceId, targetShardingDataSourceId);
			
			source_sqls.append(dynamicDataSqls.get("source_sqls"));
			target_sqls.append(dynamicDataSqls.get("target_sqls"));
			op_sqls.append(dynamicDataSqls.get("op_sqls"));
			
			if(index == 0){
				source_key.append(dynamicDataSqls.get("source_key"));
				target_key.append(dynamicDataSqls.get("target_key"));
				op_key.append(dynamicDataSqls.get("op_key"));
			}
			index = index + 1;
		}
		if(source_sqls.toString().endsWith(",")){
			source_sqls.deleteCharAt(source_sqls.length()-1).append(";");
		}
		if(target_sqls.toString().endsWith(",")){
			target_sqls.deleteCharAt(target_sqls.length()-1).append(";");
		}
		if(op_sqls.toString().endsWith(",")){
			op_sqls.deleteCharAt(op_sqls.length()-1).append(";");
		}
		*/
		//************多值插入************
		
		
		//批量提交
		if(sourceDataSource != null){//分库分表
			batchSummitSqls(sourceDataSource.getDbUser(), sourceDataSource.getDbPassword(), sourceDataSource.getDbUrl(), source_op_sqls);
			//batchSummitMutilValueSqls(sourceDataSource.getDbUser(), sourceDataSource.getDbPassword(), sourceDataSource.getDbUrl(), source_key.append(source_sqls).toString());
			//batchSummitMutilValueSqls(sourceDataSource.getDbUser(), sourceDataSource.getDbPassword(), sourceDataSource.getDbUrl(), op_key.append(op_sqls).toString());
		}else{
			String url = XxlConfClient.get("dal.jdbc.url", "");
			String user = XxlConfClient.get("dal.jdbc.username", "");
			String password = XxlConfClient.get("dal.jdbc.password", "");
			batchSummitSqls(user, password, url, source_op_sqls);
			//batchSummitMutilValueSqls(user, password, url, source_key.append(source_sqls).append(op_key).append(op_sqls).toString());
		}
		if(targetDataSource != null){//分库分表
			batchSummitSqls(targetDataSource.getDbUser(), targetDataSource.getDbPassword(), targetDataSource.getDbUrl(), target_sql);
			//batchSummitMutilValueSqls(targetDataSource.getDbUser(), targetDataSource.getDbPassword(), targetDataSource.getDbUrl(), target_key.append(target_sqls).toString());
		}else{
			String url = XxlConfClient.get("dal.jdbc.url", "");
			String user = XxlConfClient.get("dal.jdbc.username", "");
			String password = XxlConfClient.get("dal.jdbc.password", "");
			batchSummitSqls(user, password, url, target_sql);
			//batchSummitMutilValueSqls(user, password, url, target_key.append(target_sqls).toString());
		}
	}
	//批量提交sql语句
	public void batchSummitSqls(String user,String password,String url,List<String> sqls){
		Connection conn = null;
		try {
			conn = DriverManager.getConnection(url,user,password);
			JdbcUtils.batchInsert(conn, sqls);
		} catch (SQLException e) {
			e.printStackTrace();
			return ;
		}finally {
			// 关闭
			if (conn != null)
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			conn = null;
		}
	}
	//批量提交sql语句
	public void batchSummitMutilValueSqls(String user,String password,String url,String sqls){
		Connection conn = null;
		try {
			conn = DriverManager.getConnection(url,user,password);
			JdbcUtils.batchMutilValueInsert(conn, sqls);
		} catch (SQLException e) {
			e.printStackTrace();
			return ;
		}finally {
			// 关闭
			if (conn != null)
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			conn = null;
		}
	}
	/*对检索结果字段值进行Unicode转字符串*/
	public List<Map<String, Object>> unicode2String(List<Map<String, Object>>r){
		List<Map<String, Object>> lm = new ArrayList<Map<String,Object>>();
		Map<String, Object> m = null; 
		for (Map<String, Object> map : r) {
			m = new HashMap<String, Object>();
			for (String key: map.keySet()) {
				if(map.get(key) != null){
					m.put(key, UnicodeConverter.unicode2String(String.valueOf(map.get(key))));
				}
			}
			lm.add(m);
			m = null;
		}
		return lm;
	}
	
	
	/*************************************************************/
	/***************   start 带附件发布                ***********************/
	/*************************************************************/
	@Override
	public List<ModifiableSolrParams> getIndexDataWithAttachment(String classesEn, List<Map<String, Object>> list,
		String shardingDataSourceId, String tableName) {
		List<ModifiableSolrParams> r = new ArrayList<ModifiableSolrParams>();
		// 查询类
		HashMap<String, Object> queryParams = new HashMap<>();
		queryParams.put("=,nameEn", classesEn);
		List<Classes> classesList = publicService.getClasses(queryParams, 1, 1);
		Classes aClasses = null;
		if (classesList.size() > 0) {
			aClasses = classesList.get(0);
		} else {
			return null;
		}
		for (int k = 0; k < list.size(); k++) {
			Map<String, Object> data = list.get(k);
			r.add(buildSolrModifiableSolrParams(data, aClasses, shardingDataSourceId,
					tableName));
		}
		return r;
	}

	@Override
	public void submitDynamicDataWithAttachment(String classesEn, String submitTime, String submitUserId,
			String shardingDataSourceId, String tableName) {
		// 删除类下所有索引
		// deleteIndexByClassesEn(classesEn);
		int pageSize = 1000;
		String id = "0";
		System.out.println(">>>资源库开始发布："+classesEn);
		System.out.println(">>>开始id："+id);
		List<Map<String, Object>> dynamicData = getDynamicData(classesEn, id , pageSize, shardingDataSourceId, tableName);
		while(dynamicData!=null && dynamicData.size()>0){
			submitCommitIndexWithAttachment(classesEn, dynamicData, shardingDataSourceId, tableName);
			id=dynamicData.get(dynamicData.size()-1).get("id").toString();
			System.out.println(">>>结束id："+id);
			dynamicData = null;
			dynamicData = getDynamicData(classesEn, id , pageSize, shardingDataSourceId, tableName);
		}
	}

	@Override
	public void submitDynamicDataWithAttachment(String classesEn, String submitTime, String submitUserId, String id,
			String shardingDataSourceId, String tableName) {
		Map<String, Object> map = findDynamicData(classesEn, id,
				shardingDataSourceId, tableName);
		if (map != null) {
			// 发布至solr
			submitDataToSolr(map, classesEn, shardingDataSourceId, tableName);
		}
	}

	@Override
	public void submitCommitIndexWithAttachment(String classesEn, List<Map<String, Object>> list,
			String shardingDataSourceId, String tableName) {
		
		List<Map<String, Object>> temp=new ArrayList<Map<String,Object>>();
		List<Map<String, Object>> temp1=new ArrayList<Map<String,Object>>();
		List<Map<String, Object>> temp2=new ArrayList<Map<String,Object>>();
		 
		//获取附件字段
		HashMap<String, Object> queryParams = new HashMap<String, Object>();
		queryParams.put("=,nameEn", classesEn);
		List<Classes> classes = publicService.getClasses(queryParams, 1, 1);
		List<DataProperty> dataProperty = publicService.getDataProperty(classes.get(0));
		boolean fj=false;
		boolean pdf=false;
		for (DataProperty dataProperty2 : dataProperty) {
			if(dataProperty2.getNameEn().equals("fj")){
				fj=true;
				break;
			}
			if(dataProperty2.getNameEn().equals("pdf")){
				pdf=true;
			}
		}
		 
		if(fj){
			for (Map<String, Object> map : list) {
				if(map.get("fj")!=null && !"".equals(map.get("fj"))){
					temp1.add(map);
				}else{
					temp2.add(map);
				}
			}
		}else{
			if(pdf){
				for (Map<String, Object> map : list) {
					if(map.get("pdf")!=null && !"".equals(map.get("pdf"))){
						temp1.add(map);
					}else{
						temp2.add(map);
					}
				}
			}else{
				temp2=list;
			}
		}
		list=null;
		//发布不带附件的
		if(temp2!=null && temp2.size()>0){
			submitCommitIndex(classesEn, temp2, shardingDataSourceId, tableName);
		}
		temp2 = null;
		List<ModifiableSolrParams> indexData = getIndexDataWithAttachment(classesEn, temp1,
				shardingDataSourceId, tableName);
		try {
			for (int i = 0; i < indexData.size(); i++) {
				
				ModifiableSolrParams msp = indexData.get(i);
				Map<String, Object> data = temp1.get(i);
				String fileName = "";
				fileName = (String) data.get("fj");
				if(fileName != null && !"".equals(fileName)){
					String[] split = fileName.split("%");
					fileName = split[0];
				}else{
					fileName = (String) data.get("pdf");
				}
				//fileName="/upload/file/20170714/1500016248862062622.pdf";
				fileName = XxlConfClient.get("dal.file.path", "") + fileName.replace("//", "/");
				if(fileName==null || "".equals(fileName) || !new File(fileName).exists()){
					System.out.println(">>>附件不存在：classesEn="+classesEn+"\tid="+data.get("id")+"\tshardingDataSourceId="+shardingDataSourceId+"\t tableName="+tableName);
					temp.add(temp1.get(i));
				}else{
					ContentStreamUpdateRequest up = new ContentStreamUpdateRequest("/update/extract");
					try {
						//fileName="/upload/file/20170714/1500016248862062622.pdf";
						//fileName = XxlConfClient.get("dal.file.path", "") + fileName.replace("//", "/");
						up.addFile(new File(fileName),getFileContentType(fileName));
						up.setParams(msp);
						up.setAction(AbstractUpdateRequest.ACTION.COMMIT, true, true);
						server.request(up);
						System.out.println(">>>发布成功：classesEn="+classesEn+"\tid="+data.get("id")+"\tshardingDataSourceId="+shardingDataSourceId+"\t tableName="+tableName);
					} catch (Exception e) {
						System.out.println(e.getMessage());
						System.out.println(">>>附件发布失败：classesEn="+classesEn+"\tid="+data.get("id")+"\tshardingDataSourceId="+shardingDataSourceId+"\t tableName="+tableName);
						temp.add(temp1.get(i));
					}
					
					up = null;
				}
			}
			//server.commit();
			if(temp.size()>0){
				submitCommitIndex(classesEn, temp, shardingDataSourceId, tableName);
			}
			indexData =null;
			temp = null;
			temp1 = null;
		} catch (Exception e) {
			LOG.error("批量创建索引失败.", e);
			e.printStackTrace();
		}
	}
	private ModifiableSolrParams buildSolrModifiableSolrParams(Map<String, Object> data,
			Classes aClasses, String shardingDataSourceId, String tableName) {
		ModifiableSolrParams msp = new ModifiableSolrParams();
		try {
			// 查询类对象属性
			List<ObjectProperty> opList = publicService
					.getObjectProperty(aClasses);
			for (int i = 0; i < opList.size(); i++) {

				ObjectProperty aObjectProperty = opList.get(i);
				// 对象属性关联字段
				String relevanceClassFields = aObjectProperty
						.getRelevanceClassFields();
				// 查询对象属性值，需要判断分库分表信息
				List<Map<String, Object>> opDataList = null;
				if (shardingDataSourceId != null
						&& !"".equals(shardingDataSourceId)
						&& tableName != null && !"".equals(tableName)) {
					opDataList = getDynamicObjectData(aClasses.getNameEn(),
							data.get("id").toString(), null,
							aObjectProperty.getId(), 1, Integer.MAX_VALUE,
							shardingDataSourceId, tableName);
				} else {
					opDataList = getDynamicObjectData(aClasses.getNameEn(),
							data.get("id").toString(), null,
							aObjectProperty.getId(), 1, Integer.MAX_VALUE);
				}
				String[] opDataArray = new String[opDataList.size()];

				for (int j = 0; j < opDataList.size(); j++) {
					Map<String, Object> opMap = opDataList.get(j);
					// 查询关联表
					Classes targetClasses = publicService
							.findClasses(aObjectProperty
									.getRelevanceClassesId());
					// 查询关联数据详情，分库分表情况下从opDataList获得target_table_name名称
					Map<String, Object> targetMap = null;
					if (shardingDataSourceId != null
							&& !"".equals(shardingDataSourceId)
							&& tableName != null && !"".equals(tableName)) {
						targetMap = findDynamicData(targetClasses.getNameEn(),
								opMap.get("target_data_id").toString(),
								relevanceClassFields,
								opMap.get("target_sharding_data_source_id")
										.toString(),
								opMap.get("target_table_name").toString());
					} else {
						targetMap = findDynamicData(targetClasses.getNameEn(),
								opMap.get("target_data_id").toString(),
								relevanceClassFields);
					}
					// 关联组合值
					String relevanceData = "op_id∷" + opMap.get("id") + "≡"
							+ "target_class_en∷" + StringUtils.trim(targetClasses.getNameEn())
							+ "≡" + "target_class_zh∷"
							+ StringUtils.trim(targetClasses.getNameZh()) + "≡target_id∷"+targetClasses.getId()+"≡";
					if (targetMap != null) {
						Iterator iter = targetMap.entrySet().iterator();
						while (iter.hasNext()) {
							Map.Entry entry = (Map.Entry) iter.next();
							String oldKey = entry.getKey().toString();
							Object oldVal = entry.getValue();
							if(oldVal!=null){
								oldVal=StringUtils.trim(oldVal.toString());
							}
							relevanceData += oldKey + "∷" + oldVal + "≡";
						}
						opDataArray[j] = relevanceData.substring(0,
								relevanceData.length() - 1);
					}
					// 根据op对应字段判断是否需要拆分，分开存储字段
					//
				}
				msp.add("literal.stringIMS_" + aObjectProperty.getNameEn()
						+ "_data", opDataArray);

			}

			// 分库分表信息
			if (shardingDataSourceId != null
					&& !"".equals(shardingDataSourceId)) {
				msp.add("literal.stringIS_shardingDataSourceId",
						shardingDataSourceId);
			}
			if (tableName != null && !"".equals(tableName)) {
				msp.add("literal.stringIS_tableName", tableName);
			}

			// 查询类数据属性（字段）
			List<DataProperty> dpList = publicService.getDataProperty(aClasses);
			msp.add("literal.stringIS_classEn", aClasses.getNameEn());
			msp.add("literal.type", aClasses.getNameEn());
			msp.add("literal.stringIS_classZh", aClasses.getNameZh());
			msp.add("literal.id", data.get("id").toString());
			if (!"".equals(data.get("create_time").toString())) {
				msp.add("literal.dateIS_create_time", DateUtils.ConverToDate(data
						.get("create_time").toString()).toString());
			}
			/*
			if (!"".equals(data.get("create_year").toString())) {
				sid.addField("stringIS_create_year", (data
						.get("create_year").toString()));
			}
			*/
			if (!"".equals(data.get("update_time").toString())) {
				msp.add("literal.dateIS_update_time", DateUtils.ConverToDate(data
						.get("update_time").toString()).toString());
			}
			if (!"".equals(data.get("status").toString())) {
				msp.add("literal.intIS_status", data
						.get("status").toString());
			}
			if (!"".equals(data.get("create_user_id").toString())) {
				msp.add("literal.intIS_create_user_id", data
						.get("create_user_id").toString());
			}
			if (!"".equals(data.get("classes_id").toString())) {
				msp.add("literal.intIS_classes_id", data
						.get("classes_id").toString());
			}
			for (int m = 0; m < dpList.size(); m++) {
				DataProperty aDataProperty = dpList.get(m);
				DataType aDataType = publicService.findDataType(aDataProperty
						.getDataTypeId());
				String multiLanguage = "";
				String dataType = "";
				String solrFieldValue = null;
				String[] solrFieldValueArray = null;

				Object value = data.get(aDataProperty.getNameEn());

				if (aDataType.getSolrType().equals("string_auto")) {
					multiLanguage = "1";
					dataType = "string";
					if (value != null) {
						// solrFieldValue = "en,zh-cn|" + value.toString();
						//solrFieldValue = LangDetectUtils.detectLangsAndWrap(value.toString());
						solrFieldValue = StringUtils.trim(value.toString());
					}
				} else {
					multiLanguage = "0";
					dataType = aDataType.getSolrType();
					if (value != null && !"".equals(value.toString())
							&& !" ".equals(value.toString())) {
						// 判断字段多值情况
						if ("1".equals(aDataProperty.getMultiValued())) {
							// separator
							if (!"".equals(value.toString())) {
								solrFieldValueArray = value.toString().split(
										aDataProperty.getSeparator());
							}
						} else {
							solrFieldValue = StringUtils.trim(value.toString());
						}
					}
				}

				String solrField = FieldPrefixUtils.getDynamicField(dataType,
						null, multiLanguage, aDataProperty.getIndexed(),
						aDataProperty.getMultiValued(),
						aDataProperty.getStored(),
						aDataProperty.getTermVectors(),
						aDataProperty.getRequired());
				if (dataType.equals("date")) {
					if (!"".equals(solrFieldValue)) {
						msp.add("literal."+solrField + aDataProperty.getField(),
								DateUtils.ConverToDate(solrFieldValue)==null?null:DateUtils.ConverToDate(solrFieldValue).toString());
					} else {
						msp.add("literal."+solrField + aDataProperty.getField(), null);
					}
				} else if (dataType.equals("double")) {
					if (!"".equals(solrFieldValue)
							&& !"null".equals(solrFieldValue)) {
						msp.add("literal."+solrField + aDataProperty.getField(),
								solrFieldValue);
					} else {
						msp.add("literal."+solrField + aDataProperty.getField(), null);
					}
				} else if (dataType.equals("int")) {
					if (!"".equals(solrFieldValue)
							&& !"null".equals(solrFieldValue)
							&& CodeUtils.isNumeric(solrFieldValue)) {
						msp.add("literal."+solrField + aDataProperty.getField(),
								solrFieldValue);
					} else {
						msp.add("literal."+solrField + aDataProperty.getField(), null);
					}
				} else {
					// 判断字段多值情况
					if ("1".equals(aDataProperty.getMultiValued())&& solrFieldValueArray!=null) {
						for (String string : solrFieldValueArray) {
							msp.add("literal."+solrField + aDataProperty.getField(),StringUtils.trim(string));
						}
					} else {
						if (!"".equals(solrFieldValue)
								&& (!"en,zh-cn|".equals(solrFieldValue)
										|| !"en|".equals(solrFieldValue) || !"zh-cn|"
											.equals(solrFieldValue))) {
							msp.add("literal."+solrField + aDataProperty.getField(),
									solrFieldValue);
						}
						//
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		msp.add("fmap.content", "auto_stringITS_full_text");
		msp.add("uprefix", "ignored_");
		return msp;
	}
	// 发布类数据至solr
	private void submitDataToSolr(Map<String, Object> data, String classesEn,
			String shardingDataSourceId, String tableName) {
		HashMap<String, Object> r = new HashMap<String, Object>();
		// 查询类
		HashMap<String, Object> queryParams = new HashMap<>();
		queryParams.put("=,nameEn", classesEn);
		List<Classes> classesList = publicService.getClasses(queryParams, 1, 1);
		Classes aClasses = null;
		if (classesList.size() > 0) {
			aClasses = classesList.get(0);
		} else {
			return;
		}
		ContentStreamUpdateRequest up = new ContentStreamUpdateRequest("/update/extract");
		try {
			ModifiableSolrParams msp = buildSolrModifiableSolrParams(data, aClasses,shardingDataSourceId, tableName);
			String fileName = "";
			fileName = (String) data.get("fj");
			if(fileName!=null && !"".equals(fileName)){
				String[] split = fileName.split("%");
				fileName = split[0];
			}else{
				fileName = (String) data.get("pdf");
			}
			//fileName="/upload/file/20170714/1500016248862062622.pdf";
			fileName = XxlConfClient.get("dal.file.path", "") + fileName.replace("//", "/");
			if(fileName==null || "".equals(fileName) || !new File(fileName).exists()){
				System.out.println(">>>附件不存在：classesEn="+classesEn+"\tid="+data.get("id")+"\tshardingDataSourceId="+shardingDataSourceId+"\t tableName="+tableName);
				submitDataForSolr(data, classesEn, shardingDataSourceId, tableName);
			}else{
				try {
					//fileName="/upload/file/20170714/1500016248862062622.pdf";
					//fileName = XxlConfClient.get("dal.file.path", "") + fileName.replace("//", "/");
					up.addFile(new File(fileName),getFileContentType(fileName));
					up.setParams(msp);
					up.setAction(AbstractUpdateRequest.ACTION.COMMIT, true, true);
					server.request(up);
					System.out.println(">>>发布完成");
				} catch (Exception e) {
					e.printStackTrace();
					System.out.println(">>>附件发布失败：classesEn="+classesEn+"\tid="+data.get("id")+"\tshardingDataSourceId="+shardingDataSourceId+"\t tableName="+tableName);
					submitDataForSolr(data, classesEn, shardingDataSourceId, tableName);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		up = null;
	}
	public static String getFileContentType(String fileName) throws IOException {
		Path path = Paths.get(fileName);
		String contentType = Files.probeContentType(path);
		return contentType;
	}
	/*************************************************************/
	/***************   end   带附件发布                ***********************/
	/*************************************************************/
}
